XML 應用
本章演示了一些使用 XML、HTTP、DOM 和 JavaScript 的 HTML 應用。
使用的 XML 文件
在本章中,我們將使用名為 "cd_catalog.xml" 的 XML 檔案。
在 HTML 表格中顯示 XML 資料
此示例迴圈遍歷每個 <CD> 元素,並在 HTML 表格中顯示 <ARTIST> 和 <TITLE> 元素的值。
示例
<table id="demo"></table>
<script>
function loadXMLDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
const xmlDoc = xhttp.responseXML;
const cd = xmlDoc.getElementsByTagName("CD");
myFunction(cd);
}
xhttp.open("GET", "cd_catalog.xml");
xhttp.send();
}
function myFunction(cd) {
let table="<tr><th>Artist</th><th>Title</th></tr>";
for (let i = 0; i < cd.length; i++) {
table += "<tr><td>" +
cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
自己動手試一試 »
有關使用 JavaScript 和 XML DOM 的更多資訊,請轉至 DOM 入門。
在 HTML div 元素中顯示第一張 CD
此示例使用一個函式來顯示 id="showCD" 的 HTML 元素中的第一張 CD 元素。
示例
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
const xmlDoc = xhttp.responseXML;
const cd = xmlDoc.getElementsByTagName("CD");
myFunction(cd, 0);
}
xhttp.open("GET", "cd_catalog.xml");
xhttp.send();
function myFunction(cd, i) {
document.getElementById("showCD").innerHTML =
"Artist: " +
cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
cd[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
自己動手試一試 »
在 CD 之間導航
要在上面的示例中導航 CD,請建立一個 next()
和 previous()
函式。
示例
function next() {
// 顯示下一張 CD,除非您已在最後一張 CD
if (i < len-1) {
i++;
displayCD(i);
}
}
function previous() {
// 顯示上一張 CD,除非您已在第一張 CD
if (i > 0) {
i--;
displayCD(i);
}
}
自己動手試一試 »
點選 CD 時顯示專輯資訊
最後一個示例演示瞭如何在使用者點選 CD 時顯示專輯資訊。
示例
function displayCD(i) {
document.getElementById("showCD").innerHTML =
"Artist: " +
cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
cd[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}
自己動手試一試 »