要讓 jQuery 直接呼叫 .asmx Web 服務,有一個必須條件常被忽略:類別上一定要加 [ScriptService],否則前端怎麼呼叫都會失敗。本文示範如何取回 ArrayList 並塞進下拉選單。
後端回傳的 ArrayList 裡裝的是 CollegeDepartInfo 物件,屬性為 string CollegeDepartTitle 與 int CollegeDepartId。前端組 option 時就是靠這兩個屬性:
ddlDepart.options[ddlDepart.length] = new Option(n.CollegeDepartTitle, n.CollegeDepartId);
$.ajax({
type: "POST", // 明確指定 POST
contentType: "application/json;utf-8", // 要求與回傳皆為 JSON
url: "CollegeDepartWebServices.asmx/GetCollegeDepart", // 服務名/方法名
data: "{strDepartId:" + collegeId + "}", // 參數名稱 strDepartId
dataType: "json",
success: function (result) {
var json = null;
try {
if (result) {
// 回傳的是 ArrayList,逐一取出塞進下拉選單
$.each(result, function (i, n) {
ddlDepart.options[ddlDepart.length] = new Option(n.CollegeDepartTitle, n.CollegeDepartId);
});
}
} catch (e) {
alert("錯誤 >> " + e.message);
return;
}
},
error: function (data) {
alert(data.status + ">>> " + data.statusText);
}
});
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService] // 少了這行,ajax 就呼叫不到
public class CollegeDepartWebServices : System.Web.Services.WebService
{
public CollegeDepartWebServices() { }
[WebMethod]
[System.Xml.Serialization.XmlInclude(typeof(CollegeDepartInfo))]
public ArrayList GetCollegeDepart(string strDepartId)
{
CollegeDepartBL.FlushCollegeDepartCache();
if (string.IsNullOrEmpty(strDepartId)) return null;
return CollegeDepartBL.GetCollegeDepartListBySchoolID(int.Parse(strDepartId));
}
}
三個容易出錯的地方值得記住:[ScriptService] 必須加;contentType 要設為 application/json;utf-8;URL 必須寫成「服務檔名/方法名」的形式。另外若回傳的集合型別較複雜,可考慮改用 PageMethod 或 Web API,序列化行為會更單純。