做 Ajax 時,很多人習慣每支請求背後配一個後端頁面,甚至幻想著能直接呼叫 C# 類別裡的方法。好消息是這件事本來就做得到——.NET 的 [WebMethod] 加上 jQuery 的 $.ajax(),就能讓前端直接打後端方法,不用再包一層 aspx。
以下用同一支 CalledByJquery.asmx,示範四種常見組合。所有請求共用的設定是 type: "POST" 與 contentType: "application/json; charset=utf-8",這兩項沒給對,回傳就會是 XML 而不是 JSON。
$("#btn1").click(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CalledByJquery.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(json) { alert(json.d); },
error: function(error) {
alert("調用出錯" + error.responseText);
}
});
});
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
注意 success 裡取的是 json.d,那個 d 是 ASP.NET 為了防範 JSON 劫持而自動包的外層,不是方法回傳的內容本身。
$("#btn2").click(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CalledByJquery.asmx/SimpleReturns",
data: "{name:'張三'}",
dataType: "json",
success: function(json) { alert(json.d); },
error: function(error) {
alert("調用出錯" + error.responseText);
}
});
});
[WebMethod]
public string SimpleReturns(string name)
{
return String.Format("您的姓名是{0}", name);
}
傳入的 data 是 JSON 字串,物件的屬性名稱必須跟方法簽章裡的參數名完全一致,大小寫也要對得上,否則後端收到的會是 null。
$("#btn3").click(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CalledByJquery.asmx/GetStudentList",
data: "{stu:{ID:'6',Name:'ff'}}",
dataType: "json",
success: function(json) { alert(json.d); },
error: function(error) {
alert("調用出錯" + error.responseText);
}
});
});
[WebMethod]
public List<Student> GetStudentList(Student stu)
{
List<Student> studentList = new List<Student>
{
new Student{ID=1, Name="張三"},
new Student{ID=2, Name="李四"}
};
// 把客戶端傳來的實體併進回傳清單
studentList.Add(stu);
return studentList;
}
自訂類別要能被序列化,記得標上 [Serializable],屬性也要是公開的 getter/setter。前端傳的物件結構同樣得跟類別定義對應。
$("#btn4").click(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CalledByJquery.asmx/ReturnNoNameClass",
data: "{}",
dataType: "json",
success: function(json) { alert(json.d); },
error: function(error) {
alert("調用出錯" + error.responseText);
}
});
});
[WebMethod]
public object ReturnNoNameClass()
{
return new { ID = 1, Name = "張三" };
}
不想為了回傳而專門定義一個類別時,匿名物件很省事,前端一樣用 json.d.ID、json.d.Name 取值。
這些東西其實都不難,只是如果沒人提,而實際專案裡又碰不到,就會一直繞遠路——每支請求都多開一個後端頁面,長期下來檔案數量與維護成本都很可觀。把 $.ajax() 直接對準 WebService,是個能立刻簡化架構的小改動。
補充一點:ASMX Web Service 屬於較早期的技術,新專案若沒有既有包袱,改用 Web API 會更好維護;但 $.ajax() 的呼叫寫法與上面幾乎一致,觀念完全通用。