一個完整的 $.getJSON 案例,前端負責請求與渲染,後端以 ashx 一般處理常式回傳字串。
function SelectProject() {
var r = window.showModalDialog('SelProject.aspx', [], "dialogWidth=1000px; dialogHeight=600px; resizable=yes");
if (typeof (r) != 'undefined') {
var arr = r.split(";");
$("#hidProjectInnerID").val(arr[0]);
$("#txtProjectNo").val(arr[1]);
$.getJSON("../Handler/GetProjectInfor.ashx",
{ key: "PaymentStatement", InnerID: $("#hidProjectInnerID").val() },
function (json) {
$("#labFinalCustomer").text(json.finalclient);
$("#labOrderNo").text(json.orderno);
var rows = "";
$.each(json.workinghours, function (i, item) {
rows += "<tr><td>" + item.description + "</td>"
+ "<td>" + item.hoursdays + "</td>"
+ "<td>" + item.workinghour + "</td></tr>";
});
$("#infor").append(rows);
});
}
}
string innerid = GetRequest<string>("InnerID", "");
string key = GetRequest<string>("key", "");
if (key == "PaymentStatement" && innerid != "")
context.Response.Write(PaymentStatement(innerid));
PaymentStatement 依 InnerID 查主檔,組出含 finalclient、orderno 與 workinghours 陣列的 JSON;GetWorkingHours 則把明細逐列 append 成 {"innerid":"..","description":"..","workinghour":"..","hoursdays":".."} 形式的物件串。
第一,原範例的字串拼接缺少左引號(例如 json.Append(""innerid":""+...)),這樣產生的不是合法 JSON。更根本的解法是別手湊字串,改用 Response.ContentType = "application/json" 搭配 JSON.NET 的 JsonConvert.SerializeObject(),格式與跳脫都會自動處理好。
第二,SQL 直接把 innerid 內插進指令字串,存在 SQL Injection 風險。應改用參數化查詢(SqlParameter),這是基本要求而非選項。另外 GetWorkingHours 迴圈中讀的都是 Rows[0],導致每一列內容相同,應改為 Rows[i]。