使用原生 XMLHttpRequest 異步請求 XML 文件,解析 responseXML DOM 樹,提取節點數據動態生成 HTML 表格,無需刷新頁面。
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url) {
var xmlhttp, txt, x, xx, i;
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
txt = "<table border='1'><tr><th>Title</th><th>Artist</th></tr>";
x = xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
for (i = 0; i < x.length; i++) {
txt += "<tr>";
xx = x[i].getElementsByTagName("TITLE");
try { txt += "<td>" + xx[0].firstChild.nodeValue + "</td>"; }
catch (er) { txt += "<td> </td>"; }
xx = x[i].getElementsByTagName("ARTIST");
try { txt += "<td>" + xx[0].firstChild.nodeValue + "</td>"; }
catch (er) { txt += "<td> </td>"; }
txt += "</tr>";
}
txt += "</table>";
document.getElementById('txtCDInfo').innerHTML = txt;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="txtCDInfo">
<button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button>
</div>
</body>
</html>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
</CD>
...
</CATALOG>
ActiveXObject 回退。responseXML 返回解析後的 Document 物件,可用 DOM 方法遍歷。try...catch 防止節點缺失報錯。innerHTML 渲染表格。現代項目建議使用 fetch + DOMParser 或 jQuery $.ajax({dataType:'xml'}),代碼更簡潔。