แอปพลิเคชัน XML
บทนี้สาธิตแอปพลิเคชัน HTML บางตัวโดยใช้ XML, HTTP, DOM และ JavaScript
เอกสาร XML ที่ใช้
ในบทนี้เราจะใช้ไฟล์ XML ชื่อ"cd_catalog.xml "
แสดงข้อมูล XML ในตาราง HTML
ตัวอย่างนี้วนซ้ำในแต่ละองค์ประกอบ <CD> และแสดงค่าขององค์ประกอบ <ARTIST> และ <TITLE> ในตาราง HTML:
ตัวอย่าง
<table id="demo"></table>
<script>
function loadXMLDoc() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const xmlDoc = xml.responseXML;
const cd = xmlDoc.getElementsByTagName("CD");
myFunction(cd);
}
xmlhttp.open("GET", "cd_catalog.xml");
xmlhttp.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 Intro
แสดงซีดีแผ่นแรกใน HTML div Element
ตัวอย่างนี้ใช้ฟังก์ชันเพื่อแสดงองค์ประกอบซีดีแรกในองค์ประกอบ HTML ที่มี id="showCD":
ตัวอย่าง
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;
}
นำทางระหว่างซีดี
ในการนำทางระหว่างแผ่นซีดีในตัวอย่างด้านบน ให้สร้าง a
next()
และprevious()
ฟังก์ชัน:
ตัวอย่าง
function next()
{
// display the next CD, unless you are on the last CD
if (i < len-1) {
i++;
displayCD(i);
}
}
function previous()
{
// display the previous CD, unless you are on the first CD
if (i > 0) {
i--;
displayCD(i);
}
}
แสดงข้อมูลอัลบั้มเมื่อคลิกบนซีดี
ตัวอย่างสุดท้ายแสดงให้เห็นว่าคุณสามารถแสดงข้อมูลอัลบั้มได้อย่างไรเมื่อผู้ใช้คลิกที่ซีดี:
ตัวอย่าง
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;
}