The XMLHttpRequest object has a responseXML property that can be used to receive XML data from a web server. In the previous tutorial, we investigated how to use the responseText property to receive text data
from the web server. The responseText property cannot be used to parse through XML data. We are going to look at how we can use the responseXML property in more detail.
HTML Example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadAjax() {
var xhr = false;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
}
else {
// IE5/IE6
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc=xhr.responseXML;
xmlData="";
x=xmlDoc.getElementsByTagName("name");
for (i=0;i<x.length;i++)
{
xmlData=xmlData + x[i].childNodes[0].nodeValue + ", ";
}
document.getElementById("div1").innerHTML = xmlData;
}
xhr.open("GET", "/demo/ajax_load.txt", true);
xhr.send(null);
}
}
}
</script>
</head>
<body>
<img id="img1" onclick="loadAjax()" src="go.png" /> ;
<div id="div1"> <!-- Some Content --> </div>
</body>
</html>
Syntax
xhr.responseXML;
responseXML Property
If the response from the web server is XML, you will need to parse it as an XML object. Use the responseXML property.
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc=xhr.responseXML;
xmlData="";
x=xmlDoc.getElementsByTagName("name");
for (i=0;i<x.length;i++)
{
xmlData=xmlData + x[i].childNodes[0].nodeValue + ", ";
}
document.getElementById("div1").innerHTML = xmlData;
}
}
}
XML File Conents
<?xml version="1.0" encoding="utf-8" ?>
<company>
<employee>
<name>John Smith</name>
<tile>Clerk</tile>
<age>25</age>
</employee>
<employee>
<name>Jane Watson</name>
<tile>Manager</tile>
<age>35</age>
</employee>
<employee>
<name>Sally Franco</name>
<tile>Accountant</tile>
<age>40</age>
</employee>
</company>
responseXML Example
Click the icon to load XML data!
Did you find the page informational and useful? Share it using one of your favorite social sites.
Recommended Books & Training Resources