Ứng dụng XML
Chương này trình bày một số ứng dụng HTML sử dụng XML, HTTP, DOM và JavaScript.
Tài liệu XML được sử dụng
Trong chương này, chúng ta sẽ sử dụng tệp XML có tên "cd_catalog.xml" .
Hiển thị Dữ liệu XML trong Bảng HTML
Ví dụ này lặp lại từng phần tử <CD> và hiển thị giá trị của phần tử <ARTIST> và <TITLE> trong bảng HTML:
Thí dụ
<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>
Để biết thêm thông tin về cách sử dụng JavaScript và DOM XML, hãy truy cập Giới thiệu DOM.
Hiển thị CD đầu tiên trong phần tử div HTML
Ví dụ này sử dụng một hàm để hiển thị phần tử CD đầu tiên trong phần tử HTML với id = "showCD":
Thí dụ
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;
}
Điều hướng giữa các đĩa CD
Để điều hướng giữa các CD trong ví dụ trên, hãy tạo một
hàm next()
và previous()
:
Thí dụ
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);
}
}
Hiển thị thông tin album khi nhấp vào đĩa CD
Ví dụ cuối cùng cho thấy cách bạn có thể hiển thị thông tin album khi người dùng nhấp vào đĩa CD:
Thí dụ
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;
}