C# 如何使用ajax

 

1.首先下载ajax.dll,一个百度一下都有下载的!自行查找。

2.把ajax.dll导入到工程。右键工程-->添加引用--->浏览,找到下载好的ajax.dll文件,点击确定,这时候在工程目录下多了一个bin文件夹,里面就有ajax.dll文件,这证明引入ajax.dll成功了。

3.设置配置文件web.config。

在Web.config文件下的 <system.web>节点里面添加以下代码即可:

   

    <httpHandlers>
      <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro"/>
    </httpHandlers>
4.使用演示:4.1首先要对ajax进行注册。 在aspx.cs代码中的Page_Load方法里面对ajax进行注册,注册方式为Ajax.Utility.RegisterTypeForAjax(typeof(命名空间.类名)),假如没有命名空间可以直接写类名。代码如下:
public partial class ObjManage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Ajax.Utility.RegisterTypeForAjax(typeof(ObjManage));
    }
}
4.2编写cs的方法,供javascript调用。cs方法前端必须要有[Ajax.AjaxMethod],然后方法必须是公有public、静态static。例如:
    
   [Ajax.AjaxMethod]
    public static string getString(string str)
    {
        string strResult = "The string is " + str;
        return strResult;
    }
4.3javascript调用cs方法。调用的格式是:类名.方法名(参数),例如:
function alertString() {
            var str = ObjManage.getString("myAjax").value;
            alert(str);
        }

这样就完成了。这个是通过测试的,假如有什么问题,可留言。下面给出完成的源码,对于Web.config的代码就不给了,自己安装第3步设置配置文件web.config进行设置就OK了。cs代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ObjManage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Ajax.Utility.RegisterTypeForAjax(typeof(ObjManage));
    }

    [Ajax.AjaxMethod]
    public static string getString(string str)
    {
        string strResult = "The string is " + str;
        return strResult;
    }
}


--------------------------------------------------

aspx代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ObjManage.aspx.cs" Inherits="ObjManage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function alertString() {
            var str = ObjManage.getString("myAjax").value;
            alert(str);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="获取信息" οnclick="alertString();" />
    </div>
    </form>
</body>
</html>

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值