`.getJSON()` 是 jQuery 針對 JSON 格式資料簡化的 Ajax 方法。本文透過完整的前後端範例,示範從使用者選擇專案到動態渲染明細表的完整流程。
<!-- HTML -->
<input type="hidden" id="hidProjectInnerID">
<input type="text" id="txtProjectNo" readonly>
<span id="labFinalCustomer"></span>
<span id="labOrderNo"></span>
<table id="infor">
<thead><tr><th>說明</th><th></th><th>工時天數</th><th>倍率</th><th>工時</th><th>倍率</th><th>金額</th><th></th></tr></thead>
<tbody></tbody>
</table>
// JavaScript (jQuery)
function SelectProject() {
// 1. 開啟選擇對話框(舊式 showModalDialog,現代建議用 fetch + 模態框)
const result = window.showModalDialog('SelProject.aspx', null,
'dialogWidth=1000px; dialogHeight=600px; resizable:yes');
if (typeof result === 'undefined') return; // 使用者取消
const [innerId, projectNo] = result.split(';');
$('#hidProjectInnerID').val(innerId);
$('#txtProjectNo').val(projectNo);
// 2. 以 $.getJSON 取得專案明細
$.getJSON('../Handler/GetProjectInfor.ashx', {
key: 'PaymentStatement',
InnerID: innerId
}, function(json) {
if (!json) return; // 空資料處理
// 填寫基本資料
$('#labFinalCustomer').text(json.finalclient);
$('#labOrderNo').text(json.orderno);
// 3. 動態建構表格列
let rowsHtml = '';
$.each(json.workinghours, function(i, item) {
rowsHtml += `
<tr>
<td><label class="infor">${item.description}</label></td>
<td></td>
<td><label class="infor">${item.hoursdays}</label></td>
<td>0.8</td>
<td><label class="infor">${item.workinghour}</label></td>
<td>0.8</td>
<td><label class="infor">${item.workinghour}</label></td>
<td></td>
</tr>
`;
});
$('#infor tbody').html(rowsHtml);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error('取得專案資料失敗:', textStatus, errorThrown);
alert('載入專案資料失敗,請重試');
});
}
// GetProjectInfor.ashx.cs
public class GetProjectInfor : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "application/json; charset=utf-8";
string innerId = context.Request["InnerID"] ?? "";
string key = context.Request["key"] ?? "";
string result = "";
if (key == "PaymentStatement" && !string.IsNullOrEmpty(innerId)) {
result = PaymentStatement(innerId);
} else if (key == "StockOutApp" && !string.IsNullOrEmpty(innerId)) {
result = StockOutApp(innerId);
}
context.Response.Write(result);
}
private string PaymentStatement(string innerId) {
try {
// 1. 查詢主檔
string sqlMain = @"SELECT InnerID, pFinalClient, pOrderNo
FROM se_ProjectMain WHERE InnerID = @InnerID";
var dtMain = SqlShift.GetDataTable(sqlMain, new { InnerID = innerId }); // 參數化查詢防 SQL Injection
if (dtMain.Rows.Count == 0) return "{}";
var row = dtMain.Rows[0];
var json = new StringBuilder();
json.Append("{");
json.AppendFormat("\"innerid\":\"{0}\",", row["InnerID"]);
json.AppendFormat("\"finalclient\":\"{0}\",", EscapeJson(row["pFinalClient"].ToString()));
json.AppendFormat("\"orderno\":\"{0}\",", EscapeJson(row["pOrderNo"].ToString()));
// 2. 查詢明細
json.Append("\"workinghours\":");
json.Append(GetWorkingHours(innerId));
json.Append("}");
return json.ToString();
} catch (Exception ex) {
AppLog.Write($"專案獲取異常:{ex.Message}");
return "{}";
}
}
private string GetWorkingHours(string innerId) {
string sql = @"SELECT InnerID, wDescription, wWorkingHour, wHours_Days
FROM se_ProjectWorkingHour WHERE wProjectID = @InnerID";
var dt = SqlShift.GetDataTable(sql, new { InnerID = innerId });
if (dt.Rows.Count == 0) return "[]";
var json = new StringBuilder("[");
foreach (DataRow r in dt.Rows) {
json.Append("{");
json.AppendFormat("\"innerid\":\"{0}\",", r["InnerID"]);
json.AppendFormat("\"description\":\"{0}\",", EscapeJson(r["wDescription"].ToString()));
json.AppendFormat("\"workinghour\":\"{0}\",", r["wWorkingHour"]);
json.AppendFormat("\"hoursdays\":\"{0}\"", r["wHours_Days"]);
json.Append("},");
}
// 移除尾端逗號
if (json[json.Length - 1] == ',') json.Length--;
json.Append("]");
return json.ToString();
}
// 簡易 JSON 轉義(生產環境請用 Newtonsoft.Json / System.Text.Json)
private string EscapeJson(string s) {
return s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r").Replace("\t", "\\t");
}
public bool IsReusable => false;
}
async function selectProject() {
try {
// 假設改用模態框元件回傳 Promise
const { innerId, projectNo } = await openProjectSelectorModal();
document.getElementById('hidProjectInnerID').value = innerId;
document.getElementById('txtProjectNo').value = projectNo;
const response = await fetch(`/api/project/${innerId}/payment-statement`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const json = await response.json();
renderProjectInfo(json);
} catch (err) {
console.error(err);
showToast('載入失敗,請重試');
}
}
function renderProjectInfo(json) {
document.getElementById('labFinalCustomer').textContent = json.finalclient;
document.getElementById('labOrderNo').textContent = json.orderno;
const tbody = document.querySelector('#infor tbody');
tbody.innerHTML = json.workinghours.map(item => `
<tr>
<td><label class="infor">${escapeHtml(item.description)}</label></td>
<td></td>
<td><label class="infor">${item.hoursdays}</label></td>
<td>0.8</td>
<td><label class="infor">${item.workinghour}</label></td>
<td>0.8</td>
<td><label class="infor">${item.workinghour}</label></td>
<td></td>
</tr>
`).join('');
}
function escapeHtml(str) {
return str.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
}
從傳統 `$.getJSON` 邁向現代 `fetch` + 後端 API,不僅減少依賴,更能獲得更好的型別安全、錯誤處理與維護體驗。