ASP.NET Web Form traditionally 得靠 UpdatePanel 這種重量級元件才能做局部更新。其實只要把後端方法標上 [WebMethod],用 jQuery 的 $.ajax() 就能直接呼叫,輕量得多。
[WebMethod] 宣告,並引入 System.Web.Script.Services 命名空間。後端:
using System.Web.Script.Services;
[WebMethod]
public static string SayHello()
{
return "Hello Ajax!";
}
前端:
$(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; // 阻止表單提交
});
});
記住 data.d 這個包裝——ASP.NET 會把回傳值包進名為 d 的屬性裡,這是 3.5 之後為了防範 JSON 劫持而加的一層。
後端:
[WebMethod]
public static string GetStr(string str, string str2)
{
return str + str2;
}
前端:
$(function () {
$("#btnOK").click(function () {
$.ajax({
type: "POST",
url: "data.aspx/GetStr",
// key 必須與後端形參名稱完全一致
data: JSON.stringify({ 'str': '我是', 'str2': 'XXX' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { alert(data.d); },
error: function (err) { alert(err); }
});
return false;
});
});
參數名稱大小寫要對得上,這是常見的失敗原因。另外建議用 JSON.stringify() 產生字串,比手寫 "{'str':'我是'}" 安全——手寫時若值裡含單引號或換行就會壞掉。
後端:
[WebMethod]
public static List<string> GetArray()
{
List<string> li = new List<string>();
for (int i = 0; i < 10; i++) { li.Add(i.ToString()); }
return li;
}
前端:
$(function () {
$("#btnOK").click(function () {
$.ajax({
type: "POST",
url: "data.aspx/GetArray",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#list").html(""); // 先清空
$(data.d).each(function () {
$("#list").append("<li>" + this + "</li>");
});
},
error: function (err) { alert(err); }
});
return false;
});
});
後端:
using System.Collections;
[WebMethod]
public static Hashtable GetHash(string key, string value)
{
Hashtable hs = new Hashtable();
hs.Add("www", "yahooooooo");
hs.Add(key, value);
return hs;
}
前端:
$(function () {
$("#btnOK").click(function () {
$.ajax({
type: "POST",
url: "data.aspx/GetHash",
data: JSON.stringify({ 'key': 'haha', 'value': '哈哈!' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("key: haha ==> " + data.d["haha"] +
"\nkey: www ==> " + data.d["www"]);
},
error: function (err) { alert(err); }
});
return false;
});
});
若資料來源本身就是 XML 檔,不必經過後端,用 dataType: '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>
$(function () {
$("#btnOK").click(function () {
$.ajax({
url: "XMLtest.xml",
dataType: '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); }
});
return false;
});
});
一定要用 POST。GET 呼叫 WebMethod 預設被拒絕(這是安全設計),除非在 [WebMethod] 上明確加上 [ScriptMethod(UseGet = true)]。
回傳值一律在 data.d。寫成 data 會拿到 undefined。
WebMethod 沒有 session 保障。靜態方法拿不到 Session、Request 這些目前內容,若需要使用者狀態得另外處理。這也是為什麼正式專案多半會改用 Web API 或 MVC 的 Action——WebMethod 適合小工具與內部系統,撐不起複雜業務。