首先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);
}
};