XML — AJAX
Loading XML with AJAX
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var xmlDoc = this.responseXML;
var titles = xmlDoc.getElementsByTagName("title");
for (var i = 0; i < titles.length; i++) {
console.log(titles[i].childNodes[0].nodeValue);
}
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
Using jQuery
$.get("books.xml", function(xmlDoc) {
$(xmlDoc).find("book").each(function() {
console.log($(this).find("title").text());
});
});
Using Fetch API
fetch("books.xml")
.then(response => response.text())
.then(str => new DOMParser().parseFromString(str, "text/xml"))
.then(xmlDoc => {
var titles = xmlDoc.getElementsByTagName("title");
console.log(titles[0].textContent);
});
Practical Example
function loadBooks() {
fetch("books.xml")
.then(res => res.text())
.then(str => new DOMParser().parseFromString(str, "text/xml"))
.then(xml => {
var html = "";
xml.querySelectorAll("book").forEach(book => {
html += "<div class='book'>";
html += "<h3>" + book.querySelector("title").textContent + "</h3>";
html += "<p>" + book.querySelector("author").textContent + "</p>";
html += "</div>";
});
document.getElementById("books").innerHTML = html;
});
}
Mini Practice
- Load XML with XMLHttpRequest
- Parse the response as XML
- Extract and display data
- Use jQuery for simpler syntax
Up Next
Continue with RSS — RSS feed format in XML.
Related Topics
Frequently Asked Questions about AJAX
What is AJAX in XML?
AJAX is a fundamental concept in XML. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn AJAX?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn AJAX.
Why is AJAX important in XML?
AJAX is essential for XML development. Understanding this concept will help you write better code and solve real-world problems more effectively.