AJAX XML Example
- Previous Page AJAX Response
- Next Page AJAX PHP
AJAX can be used for interactive communication with XML files.
AJAX XML Example
The following example demonstrates how a web page can read information from an XML file using AJAX:
Example
Example Explanation
The loadDoc() function is executed when the user clicks the "Get CD Information" button.
The loadDoc() function creates an XMLHttpRequest object, adds a function to be executed when the server response is ready, and sends a request to the server.
After the server response is ready, build an HTML table, extract nodes (elements) from the XML file, and finally update the element "demo" with an HTML table filled with XML data:
LoadXMLDoc()
function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "music_list.xml", true); xhttp.send(); } function myFunction(xml) { var i; var xmlDoc = xml.responseXML; var table="<tr><th>Artist</th><th>Track</th></tr>"; var x = xmlDoc.getElementsByTagName("TRACK"); 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; }
XML File
The XML file used in the previous example is similar to this:"music_list.xml".
- Previous Page AJAX Response
- Next Page AJAX PHP