This chapter showcases several HTML applications that use XML, HTTP, DOM, and JavaScript.
In this chapter, we will work with an XML file named “cd_catalog.xml”.
This example iterates through each <CD>
element and displays the values of the <ARTIST>
and <TITLE>
elements in an HTML table.
<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) { </body> </html> |
This example uses a function to display the first <CD>
element within an HTML element with the 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; } |
To navigate through the CDs in the example above, create next() and previous() functions.
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); } } |
The last example demonstrates how to display album information when the user clicks on a 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; } |