要在 ASP.NET 的 WebService(.asmx)中允許前端腳本呼叫,必須在類別上補一個屬性,這一步很容易漏掉,漏了就會得到 500:
// 若要允許使用 ASP.NET AJAX 從腳本中呼叫此 Web 服務,請取消對下行的註解。 [System.Web.Script.Services.ScriptService]
原始碼下載:/201008/yuanma/WebService2.rar
以下依序示範無參數、有參數、集合、複合型別、DataSet 以及全域 loading 六種情境。
$(document).ready(function() {
$('#btn1').click(function() {
$.ajax({
type: "POST", // 呼叫 WebService 固定用 POST
contentType: "application/json", // 要求回傳 JSON
url: WebServiceURL + "WebService1.asmx/HelloWorld", // WsURL/方法名
data: "{}", // 無參數也要給空物件
dataType: 'json',
success: function(result) {
$('#dictionary').append(result.d);
}
});
});
});
要注意 result.d 這層包裝:ASP.NET 的 ScriptService 會把回傳值包進名為 d 的屬性裡,這是 .asmx 的慣例,也是許多人第一次呼叫時「拿到 undefined」的原因。
$(document).ready(function() {
$("#btn2").click(function() {
$.ajax({
type: "POST",
contentType: "application/json",
url: WebServiceURL + "WebService1.asmx/GetWish",
data: "{value1:'心想事成',value2:'萬事如意',value3:'牛牛牛',value4:2009}",
dataType: 'json',
success: function(result) {
$('#dictionary').append(result.d);
}
});
});
});
data 字串必須是合法 JSON,也就是 key 要用雙引号包起來。範例中為了精簡寫成單引號,實務上請改為 {"value1":"..."},否則部分瀏覽器會直接拋錯。
$(document).ready(function() {
$("#btn3").click(function() {
$.ajax({
type: "POST",
contentType: "application/json",
url: WebServiceURL + "WebService1.asmx/GetArray",
data: "{i:10}",
dataType: 'json',
success: function(result) {
$(result.d).each(function() {
$('#dictionary').append(this.toString() + " ");
});
}
});
});
});
$(document).ready(function() {
$('#btn4').click(function() {
$.ajax({
type: "POST",
contentType: "application/json",
url: WebServiceURL + "WebService1.asmx/GetClass",
data: "{}",
dataType: 'json',
success: function(result) {
$(result.d).each(function() {
$('#dictionary').append(this['ID'] + " " + this['Value']);
});
}
});
});
});
自訂類別序列化後,每個元素就是一個物件,直接用屬性名稱取值即可。
$(document).ready(function() {
$('#btn5').click(function() {
$.ajax({
type: "POST",
url: WebServiceURL + "WebService1.asmx/GetDataSet",
data: "{}",
dataType: 'xml', // 這裡改成 XML,與前面不同
success: function(result) {
try {
$(result).find("Table1").each(function() {
$('#dictionary').append(
$(this).find("ID").text() + " " + $(this).find("Value").text());
});
} catch (e) {
alert(e);
return;
}
},
error: function(result, status) {
if (status == 'error') alert(status);
}
});
});
});
$(document).ready(function() {
$('#loading')
.ajaxStart(function() { $(this).show(); })
.ajaxStop(function() { $(this).hide(); });
});
ajaxStart 與 ajaxStop 雖然是掛在某個元素上,但它們監控的其實是全域的 ajax 活動——不論由哪段程式發起的請求,都會觸發這對事件。因此同一頁只該有一處使用,否則會互相搶著控制同一個 loading 指示器。
不要用 GET 呼叫有副作用的 WebService 方法;contentType 與 dataType 是兩件不同的事,前者描述「我送出去的格式」,後者描述「我期待收到的格式」;若方法回傳 void,result.d 會不存在,success 中要先做防呆。
最後,.asmx 這套 SOAP 服務在微軟官方文件中已被標記為「基於 SOAP 的舊技術」,僅保留作相容用途。新專案若要對外提供服務,建議改用 Web API 或 WCF 的 REST 端點,前端呼叫方式會更直接,也不必再處理 result.d 這層包裝。