AJAX XML Example
AJAX can be used to interactively communicate with XML files.
AJAX XML Example
The following example demonstrates how a web page can use AJAX to read information from an XML file:
Example
Example Analysis - loadXMLDoc() Function
When a user clicks the "Get My CD Collection" button above, the loadXMLDoc() function is executed.
The loadXMLDoc() function creates an XMLHttpRequest object, adds a function to be executed when the server response is ready, and sends the request to the server.
When the server response is ready, it constructs an HTML table, extracts nodes (elements) from the XML file, and finally fills the table element with id="demo" using the XML data:
Asynchronous Loading of XML Document
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
AJAX Server Page
The server page used in this example is actually an XML file named "cd_catalog.xml".