首先AJAX的应用是建立在 服务器端 和 客户端 的交互基础之上的,这个交互的过程通过异步的方式来实现就
达到了我们现在说看到AJAX应用的效果。 因此我们要开发一个AJAX类库的话,需要大概2个模块,服务器端类库和控件,客户端脚本库。下面给我的一个AJAX库的主要源码:
ScriptManager :
public class ScriptManager : WebControl, INamingContainer
{
protected void BuildControl()
{
base.Controls.Clear();
AddJS("AjaxServer.Resource.AjaxClient.js");//输出客户端JS脚本库
foreach (ServiceItem service in _services)
{
base.Controls.Add(service);
}
}
protected override void CreateChildControls()
{
Controls.Clear();
ClearChildViewState();
BuildControl();
}
}
AjaxHandler:
public class AjaxHandler
{
public static void Handler(Page obj)
{
if (obj.Request["RegisterProxy"] == null)
{
AjaxInvoker.InvokeMethod(obj);
return;
}
AjaxRegister.RegistePage(obj);
}
}
AjaxRegister:
public class AjaxRegister
{
public static void RegistePage(Page obj)
{}//通过发射的方法得到当前Page的可用的AJAXMETHOD
//GetCustomAttributes(typeof(AjaxMethodAttribute), true)该方法可以过滤自定义AJAXMETHOD
//AjaxMethodAttribute需要你自己定义
}
AjaxInvoker:
public class AjaxInvoker
{
public static void InvokeMethod(Page obj)
{}//得到当前请求的Request["MethodName"],Request["MethodParameters"]
//并通过反射的方法实现对方法的调用的到返回值,用JSONParser(自己实现)解析后返回
//客户端。
}
--------------------------------------------------------------------------------------------------------------------------------
客户端JS脚本库,可以使用PRORTOTYPE.js,自己在扩展以下,如:
var AjaxClient = {
userCallBack : null,
Invoke : function(url,method,params,options)
{
options.postBody = "MethodName="+method+"&MethodParameters="+toJSON(params);
options.method = "post";
this.userCallBack = options.onSuccess;
options.onSuccess = this.callback.bind(this);//setup context
var myAjax = new Ajax.Request(url,options)
},
callback : function (response)
{
var result;
try
{
eval("result = "+response.responseText);
}catch(e){alert("JSON Parse Error: /n"+e.message+"/n"+response.responseText);return;}
if(result.Result)
this.userCallBack(result.Data);
else
alert("调用失败: /n"+result.Data);
}
};