萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 使用 AJAX 從 XML 文件動態獲取數據並顯示

核心思路

使用原生 XMLHttpRequest 異步請求 XML 文件,解析 responseXML DOM 樹,提取節點數據動態生成 HTML 表格,無需刷新頁面。

完整 HTML + JS 示例

<!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>

XML 數據示例 (cd_catalog.xml)

<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>

關鍵點

  • 兼容 IE5/6 使用 ActiveXObject 回退。
  • responseXML 返回解析後的 Document 物件,可用 DOM 方法遍歷。
  • try...catch 防止節點缺失報錯。
  • 動態拼接 HTML 字符串賦值給 innerHTML 渲染表格。

現代替代方案

現代項目建議使用 fetch + DOMParser 或 jQuery $.ajax({dataType:'xml'}),代碼更簡潔。

copyright © 萬盛學電腦網 all rights reserved