把 XML 資料攤成一張表格,是 Ajax 最典型的用途之一。這個範例不使用 innerHTML,而是靠 DOM 方法一格一格組出來,因此更安全也更可控。
按下按鈕 → 建立 XMLHttpRequest → 以 GET 抓取 dynamicContent.xml → 狀態變為完成後 → 先清空舊結果 → 解析 XML 並逐列附加 → 最後加上邊框。
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
} else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function doSearch() {
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open('GET', 'dynamicContent.xml', true);
xmlHttp.send(null);
}
function handleStateChange() {
if (xmlHttp.readyState !== 4 || xmlHttp.status !== 200) { return; }
clearPreviousResults();
parseResults();
}
第二次查詢前若不先清空,新資料會疊在舊資料下面。清空的方式是反覆移除子節點:
function clearPreviousResults() {
var header = document.getElementById('header');
while (header.firstChild) {
header.removeChild(header.firstChild);
}
var tableBody = document.getElementById('resultsBody');
while (tableBody.childNodes.length > 0) {
tableBody.removeChild(tableBody.childNodes[0]);
}
}
用 while 迴圈而不是 if,是因為標題區可能有不止一個子節點;原範例只移除 childNodes[0] 一次,這是一個值得修正的小 bug。
function parseResults() {
var results = xmlHttp.responseXML;
var props = results.getElementsByTagName('property');
for (var i = 0; i < props.length; i++) {
var property = props[i];
var address = property.getElementsByTagName('address')[0].firstChild.nodeValue;
var price = property.getElementsByTagName('price')[0].firstChild.nodeValue;
var comments = property.getElementsByTagName('comments')[0].firstChild.nodeValue;
addTableRow(address, price, comments);
}
var header = document.createElement('h2');
header.appendChild(document.createTextNode('查詢結果:'));
document.getElementById('header').appendChild(header);
document.getElementById('resultsTable').setAttribute('border', '1');
}
function addTableRow(address, price, comments) {
var row = document.createElement('tr');
row.appendChild(createCellWithText(address));
row.appendChild(createCellWithText(price));
row.appendChild(createCellWithText(comments));
document.getElementById('resultsBody').appendChild(row);
}
function createCellWithText(text) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(text));
return cell;
}
innerHTML 拼接字串看起來短,但有三個問題:資料若含 <、> 等字元會破壞結構;資料若含標籤則會被瀏覽器執行,形成 XSS;而且無法對個別節點做後續操作。createElement 與 createTextNode 建立的節點,內容永遠被當成純文字,天然免疫這類問題。
另外提醒兩點:回傳的 XML 若某一列缺少 comments 節點,[0].firstChild 這行會直接拋錯,正式環境應加上存在性檢查;若伺服器回傳的 Content-Type 不是 text/xml,responseXML 會是 null,此時需改用 DOMParser 解析 responseText。
頁面結構本身很簡單:一個觸發 doSearch 的按鈕、一個 id 為 header 的 span 放標題、一個 id 為 resultsTable 的表格,表內 tbody 的 id 是 resultsBody,作為新增資料列的都落點。