$.getJSON 是 jQuery 中用來向伺服器請求 JSON 資料並自動解析的簡便方法。以下以一個專案結算單的場景為例,說明前端如何取值、發請求,並把結果動態渲染成表格列。
function SelectProject() {
var a = new Array;
var r = window.showModalDialog('SelProject.aspx', a, "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 strDeviceTr = "";
$.each(json.workinghours, function (i, item) {
strDeviceTr += "<tr><td><lable name="infor">" + item.description + "</lable></td>";
strDeviceTr += "<td></td><td><lable name="infor">" + item.hoursdays + "</lable></td>";
strDeviceTr += "<td>0.8</td><td><lable name="infor">" + item.workinghour + "</lable></td>";
strDeviceTr += "<td>0.8</td><td><lable name="infor">" + item.workinghour + "</lable></td><td></td></tr>";
});
$("#infor").append(strDeviceTr);
});
}
}
後端依傳入的 key 分派不同業務,再把查詢結果組裝成 JSON 字串回傳:
string innerid = CommonClass.Request.GetRequest<string>("InnerID", "");
string key = CommonClass.Request.GetRequest<string>("key", "");
string result = "";
if (key == "StockOutApp" && innerid != "") { result = StockOutApp(innerid); context.Response.Write(result); }
else if (key == "PaymentStatement" && innerid != "") { result = PaymentStatement(innerid); context.Response.Write(result); }
public string PaymentStatement(string _innerid) {
try {
string sql = @"select InnerID,pFinalClient,pOrderNo from se_ProjectMain where InnerID='" + _innerid + "'";
DataTable dt = SqlShift.GetDataTable(sql);
if (!CommonClass.DTRow.CheckDtIsEmpty(dt)) {
StringBuilder json = new StringBuilder();
json.Append(""innerid"":" + dt.Rows[0]["InnerID"] + "");
json.Append(","finalclient":" + dt.Rows[0]["pFinalClient"] + "");
json.Append(","orderno":" + dt.Rows[0]["pOrderNo"] + "");
json.Append(","workinghours":" + GetWorkingHours(_innerid));
return "{" + json.ToString().Trim(',') + "}";
}
return string.Empty;
} catch (Exception ex) {
AppLog.Write("項目獲取異常![異常信息:" + ex.Message + "]", AppLog.LogMessageType.Info);
return string.Empty;
}
}
整體流程是:前端用 $.getJSON 送出 key 與 InnerID,後端查資料庫後組出 JSON,前端在回呼函式中用 $.each 遍歷陣列並拼出表格列。實作時建議留意 SQL 使用參數化查詢以避免注入風險,並以標準序列化函式產生 JSON 會更穩妥。