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;
}
自己动手试一试 »