在 ASP.NET 中,可以透過 jQuery 的 ajax 調用後台的 WebMethod(PageMethod)實現無刷新數據交互。本文說明在 .NET 2.0 環境下的具體配置與調用方法。
首先必須在 WebConfig 下的 system.web 節點加入以下配置信息:
<httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </httpModules>
後台方法需標註 [WebMethod] 並設置返回 JSON 格式:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
/// <summary>
/// 是否允許注冊
/// </summary>
/// <param name="MemberLoginID"></param>
/// <returns></returns>
public static MemberInfo AllowRegist(string MemberLoginID)
{
return new MemberInfo();
}
前端透過 jQuery ajax 進行調用:
$.ajax({
cache:false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: "{'MemberLoginID':'" + $("#<%=MemberLoginID.ClientID %>").val() + "'}",
dataType: 'json',
url: 'Reg.aspx/getDate',
success: function(result,x,y) {
alert(result);
},
beforeSend:function (xhr) {
xhr.setRequestHeader('If-Modified-Since', '0');
},
error: function(e) {
debugger;
}
});
關鍵點在於:contentType 需設為 'application/json',data 需為符合參數結構的 JSON 字符串,url 則採用「頁面路徑/方法名」的形式,从而正确调用后台的静态 WebMethod 并接收 JSON 数据。
希望本文所述對大家 jQuery 程序設計有所幫助。