Asp.NET 中 Ajax 的配置使用
1、下载ajax.net组件
新建一个web项目,使用.NET1.1就引用类库AjaxPro.dll,如果是使用.NET2.0 就引用AjaxPro.2.dll
AjaxPro.NET包下载,AjaxPro.dll,AjaxPro.2.dll都在里面
我用的是vs2008 .net2.0 ie7.0
2、配置web.config
在<system.web> 节点内增加
<httpHandlers>
<add verb="*"path="*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</httpHandlers>
3、空间声明,注册类名
后台代码类声明前可以设置Ajax方法空间声明,可以不设,默认为类名_Default
[AjaxPro.AjaxNamespace("myAjax")]
public partial class _Default : System.Web.UI.Page
在页面加载Page_Load事件中注册
protected void Page_Load(object sender, EventArgs e)
{
//注册当前页面类
AjaxPro.Utility.RegisterTypeForAjax(typeof(_Default));
}
4、编写服务器端方法
[AjaxPro.AjaxMethod]
public string ReturnAjax()
{
return "ajax success";
}
[AjaxPro.AjaxMethod]声明这个函数是由AJAX.NET在页面异步请求的,总之记住要通过AJAX获得数据的后台函数就使用[AjaxPro.AjaxMethod]来声明一下。
在 [AjaxPro.AjaxMethod(AjaxPro.……)] 的‘…… ’部分ajax.net还提供了其他很多方法,可以处理一些特殊的请求。
5、客户端代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MyFirstProject._Default" %>
<!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>Default页面</title>
<script language="javascript">
function myFirstAjax()
{
//alert "ajax success"
var obj= myAjax.ReturnAjax();
alert(obj.value);
//alert "ajax success"
myAjax.ReturnAjax(alertObject);
//alert "ajax success"
myAjax.ReturnAjax(function(obj){alert(obj.value);});
}
function alertObject(obj)
{
alert(obj.value);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" ID = "btnAjaxTest" runat="server" value="AJax Test" onclick="javascript:myFirstAjax()" />
</form>
</body>
</html>
浙公网安备 33010602011771号