Using AJAX (Asynchronous JavaScript and XML), you can load and read data from an external .xml file without reloading the webpage.
This is commonly used to:
XML File (cd_catalog.xml)
<catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> </cd> </catalog>
HTML + JavaScript Code:
<!DOCTYPE html>
<html>
<head>
<title>AJAX XML Example</title>
<script>
function loadXMLDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
const xmlDoc = this.responseXML;
const cds = xmlDoc.getElementsByTagName("cd");
let output = "<h3>CD List:</h3><ul>";
for (let i = 0; i < cds.length; i++) {
let title = cds[i].getElementsByTagName("title")[0].textContent;
let artist = cds[i].getElementsByTagName("artist")[0].textContent;
output += "<li><b>" + title + "</b> by " + artist + "</li>";
}
output += "</ul>";
document.getElementById("demo").innerHTML = output;
};
xhttp.open("GET", "cd_catalog.xml");
xhttp.send();
}
</script>
</head>
<body>
<h2>AJAX XML Example (W3Schools Style)</h2>
<button type="button" onclick="loadXMLDoc()">Get CD List</button>
<div id="demo"></div>
</body>
</html>
-
When you click the button, loadXMLDoc() is called.
-
It makes an AJAX request to get the cd_catalog.xml file.
-
JavaScript reads the XML data (