jQuery 的 $.ajax 讓非同步呼叫 WebService 變得相當直觀:前端把 JSON 字串當成 data 送出去,後端處理完再回傳 JSON 物件給頁面渲染。這套流程本身沒什麼難度,真正卡住人的是傳複合結構的時候。
假設前端要送的是這樣一組資料:
{
'Employee': [
{'name': 'John', 'sex': 'man', 'age': '25'},
{'name': 'Tom', 'sex': 'man', 'age': '21'}
]
}
把它作為 $.ajax 的 data 參數送出去完全沒問題,但伺服器端的方法簽名該怎麼寫?搜尋之後只找到一堆同樣在問的人,於是自己動手拆解:這裡的 Employee 本質上是一個陣列,而陣列的每一項都是一個key-value 的字典結構。那麼 C# 這邊對應的型別就很清楚了——Dictionary<string, string>[]。試了之後果然成功。
// JQuery 呼叫 webService 導入資料
function LoadData() {
$.ajax({
url: "ImportDataService.asmx/ImportStu",
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: "{'students':[{'name':'KoBe ','sex':'boy','age':'20'},{'name':'Mary','sex':'girl','age':'19'}]}",
success: function (result) {
alert(result.d);
},
error: function (e) {
alert(e.responseText);
}
});
}
幾個細節:contentType 必須宣告為 application/json,否則後端可能收不到;dataType: "json" 則保證回應會被自動解析成物件;成功回調裡的 result.d 是 ASP.NET WebService 的固定包裝格式,實際的傳回值都藏在 d 裡面。
/// <summary>
/// 批次導入學生資料
/// </summary>
/// <param name="students">學生字典陣列</param>
/// <returns>處理結果訊息</returns>
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string ImportStu(Dictionary<string, string>[] students)
{
if (students.Length == 0)
{
return "沒有任何數據!";
}
try
{
foreach (Dictionary<string, string> stu in students)
{
Student student = new Student();
foreach (string key in stu.Keys)
{
switch (key)
{
case "name":
student.Name = stu[key];
break;
case "sex":
student.Sex = stu[key];
break;
case "age":
int age;
if (Int32.TryParse(stu[key], out age))
{
student.Age = age;
}
else
{
student.Age = 0;
}
break;
}
}
// 此處可加入 student 的實際處理邏輯,例如寫入資料庫
}
return "導入學生成功!";
}
catch
{
throw new Exception("導入學生失敗!");
}
}
1. 參數名稱必須與 JSON 的 key 一致。上例中前端送的是 students,後端方法參數也必須叫 students,大小寫都要相同,否則會收到 null。
2. 務必加上 ScriptMethod 並指定 JSON 格式。少了這個 Attribute,.NET 預設的序列化器無法正確處理你送來的 JSON 字串。
另外提醒一個型別上的限制:Dictionary<string, string> 只能裝字串值。若欄位型別不確定,就全部當字串收,進到後端再自行轉型(如上例的 age 用 Int32.TryParse 處理),這樣比硬用 object 字典來得安全。