後端返回 Map<String, Object> 經 JSON 序列化後,前端常收到「對象數組」格式。本文針對此類數據結構,提供標準化解析模式與防禦性編程技巧。
// 後端 Map 列表序列化後
[
{"deptid": 1, "deptname": "技術部"},
{"deptid": 2, "deptname": "產品部"},
{"deptid": 3, "deptname": "運營部"}
]
$.ajax({
url: '/api/depts',
dataType: 'json', // 自動 JSON.parse
success: function(data) {
// data 直接是數組
$.each(data, function(index, item) {
// item 為 {deptid: 1, deptname: "技術部"}
$('#deptSelect').append(
$('
fetch('/api/depts')
.then(r => r.json())
.then(data => {
for (const item of data) {
const opt = document.createElement('option');
opt.value = item.deptid;
opt.textContent = item.deptname;
deptSelect.appendChild(opt);
}
});
// 原文代碼有隱患:for...in 遍歷原型鏈屬性,需 hasOwnProperty 守衛
for (var i in datares) {
if (datares.hasOwnProperty(i)) { // 必須保留
const item = datares[i];
sel.append(``);
}
}
// 現代寫法:Object.keys / Object.values / Object.entries
Object.values(datares).forEach(item => {
sel.append(``);
});
Array.isArray(data) && data.every(item => item.deptid != null)item.deptname ?? '未知部門'textContent 或 jQuery .text() 設置文本,避免拼接 HTMLtry...catch 包裹解析邏輯,友好降級function populateDepts(selectEl, data) {
if (!Array.isArray(data)) {
console.error('預期數組,實際收到:', data);
return;
}
const fragment = document.createDocumentFragment();
data.forEach(item => {
if (item && typeof item.deptid !== 'undefined') {
const opt = document.createElement('option');
opt.value = String(item.deptid);
opt.textContent = String(item.deptname ?? '');
fragment.appendChild(opt);
}
});
selectEl.appendChild(fragment); // 批量掛載,單次重排
}
// 使用
populateDepts(document.getElementById('deptSelect'), responseData);
面對 Map 型 JSONArray,核心就三步:確認數組 → 遍歷項目 → 安全提取鍵值。拒絕手動拼接 HTML 字符串,擁抱 DocumentFragment 與 textContent,代碼更安全、性能更優、維護更易。