借助 jQuery 的 $.ajax(),我們可以非常方便地調用 ASP.NET 的後台方法,實現無刷新交互。下面由淺入深地介紹幾種常見場景。
後台代碼需要滿足兩個前提:方法必須是 static 靜態方法,並且有 [WebMethod] 聲明。
using System.Web.Script.Services;
[WebMethod]
public static string SayHello()
{
return "Hello Ajax!";
}
前端 jQuery 代碼如下:
$(function () {
$("#btnOK").click(function () {
$.ajax({
type: "Post", // 使用 POST 方式
url: "data.aspx/SayHello", // 方法所在頁面與方法名
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d); // 返回數據用 data.d 獲取
},
error: function (err) { alert(err); }
});
return false; // 禁用按鈕的默認提交
});
});
[WebMethod]
public static string GetStr(string str, string str2)
{
return str + str2;
}
前端傳參時,鍵名必須與後台形參名稱完全一致:
$.ajax({
type: "Post",
url: "data.aspx/GetStr",
data: "{'str':'我是','str2':'XXX'}", // str、str2 對應後台形參名
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { alert(data.d); },
error: function (err) { alert(err); }
});
[WebMethod]
public static List<string> GetArray()
{
List<string> li = new List<string>();
for (int i = 0; i < 10; i++)
li.Add(i + "");
return li;
}
前端可遍歷返回的數組並逐項插入列表:
success: function (data) {
$("#list").html(""); // 插入前先清空
$(data.d).each(function () { // 遍歷數據
$("#list").append("<li>" + this + "</li>");
});
}
[WebMethod]
public static Hashtable GetHash(string key, string value)
{
Hashtable hs = new Hashtable();
hs.Add("www", "yahooooooo");
hs.Add(key, value);
return hs;
}
前端可通過鍵名取值:
data: "{ 'key': 'haha', 'value': '哈哈!' }",
// ...
success: function (data) {
alert("key: haha ==> " + data.d["haha"] + "\n key: www ==> " + data.d["www"]);
}
當後台返回的不是 JSON 而是 XML 時,只需把 dataType 改為 xml。例如 XMLtest.xml:
<?xml version="1.0" encoding="utf-8" ?> <data> <item><id>1</id><name>qwe</name></item> <item><id>2</id><name>asd</name></item> </data>
前端解析代碼:
$.ajax({
url: "XMLtest.xml",
dataType: 'xml', // 返回類型為 XML
success: function (xml) {
$("#list").html("");
$(xml).find("data>item").each(function () {
$("#list").append("<li>id:" + $(this).find("id").text() + "</li>");
$("#list").append("<li>Name:" + $(this).find("name").text() + "</li>");
});
},
error: function (result, status) { alert(status); }
});
以上就是 $.ajax() 與 ASP.NET 後台交互的五種典型用法,涵蓋了從簡單返回值到複雜數據結構的各類場景。