Ứ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 qua từng phần tử <CD> và hiển thị giá trị của phần tử <ARTIST> và <TITLE> trong bảng HTML:
Ví dụ
<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>
Hãy tự mình thử »Để biết thêm thông tin về cách sử dụng JavaScript và XML DOM, hãy truy cập phần 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 hàm để hiển thị phần tử CD đầu tiên trong phần tử HTML có id="showCD":
Ví 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;
}
Hãy tự mình thử »Điều hướng giữa các đĩa CD
Để điều hướng giữa các đĩa CD trong ví dụ trên, hãy tạo hàm next()
và previous()
:
Ví 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);
}
}
Hãy tự mình thử »Hiển thị thông tin Album khi bấm vào 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 CD:
Ví 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;
}
Hãy tự mình thử »