後端把查詢結果打包成 list 丟回來,前端要把它攤平成畫面上的內容——這是 CRUD 應用裡最日常的動作。以下是最精簡的組合寫法。
$.ajax({
type: 'POST',
url: "maintain_findRoomByBuildingId.shtml",
cache: false,
data: { "buildingId": buildingId },
dataType: 'json',
success: function (data) {
jQuery.each(data.roomList, function (i, item) {
alert(item.id + "," + item.name);
});
},
error: function () {
return;
}
});
dataType: 'json'——宣告回傳格式,jQuery 會自動把字串 parse 成物件,success 回呼收到的 data 就是可以直接取屬性的 JS 物件,不必再 JSON.parse()。
jQuery.each 的簽名——each(collection, function(index, value)),索引在前、值在後,順序容易寫反,值得記牢。若要中斷迴圈,在回呼裡 return false; 即可。
cache: false——GET 請求時會自動補上時間戳參數,避免舊 IE 或某些代理伺服器快取住查詢結果,讓使用者改了條件卻看到舊資料。
alert 只是為了示範,真正要做的是把資料塞進畫面。這時與其逐筆 DOM 操作,不如先拼字串再一次插入:
success: function (data) {
var list = data.roomList || [];
if (list.length === 0) {
$("#roomList").html("<p class='text-muted'>此棟別目前沒有房間資料</p>");
return;
}
var html = "";
$.each(list, function (i, item) {
html += '<li data-id="' + item.id + '">' + item.name + '</li>';
});
$("#roomList").html(html);
}
補一個安全提醒:上面用字串拼接 HTML,如果 item.name 來自使用者輸入,就有 XSS 風險。資料量大或欄位不可信時,改用元素方式組裝會安全得多:
var $li = $("<li>", { "data-id": item.id, text: item.name });
$("#roomList").append($li);
傳 text 而非 html,jQuery 會自動處理轉義,標籤字元會被當成純文字顯示。