Hello I'm new with AJAX and I'm trying to read an XML file with Javascript. It's supposed to display an alert message but it's not. What's wrong with my code?
Thanks!
:)
HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>XML Exercise</title>
<script type="text/javascript" src="xmlExercise.js"></script>
</head>
<body onLoad="getData()">
</body>
</html>
Javascript - xmlExercise.js
function getData()
{
var Request = false;
var docElement, childOne, childTwo, textNode, targetData;
if (window.XMLHttpRequest)
{
Request = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
Request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (Request)
{
Request.open("GET", "library.xml");
Request.onreadystatechange = function()
{
if (Request.readyState == 4 && Request.status == 200)
{
var xmlDoc = Request.responseXML;
ClearOutWhiteSpace(xmlDoc);
docElement = xmlDoc.documentElement;
childOne = docElement.firstChild;
childTwo = childOne.nextSibling;
textNode = childTwo.firstChild;
targetData = textNode.nodeValue;
window.alert("There are " + targetData + " in the library.");
}
}
}
Request.send(null);
}
function ClearOutWhiteSpace(xmlFile)
{
var i = 0;
for (i = 0; i < xmlFile.childNodes.length; i++)
{
var tag = xmlFile.chlidNodes[i];
if (tag.nodeType == 1)
{
ClearOutWhiteSpace(tag);
}
if ((tag.nodeType == 3) && (/^\s+$/.test(tag.nodeValue)))
{
xmlFile.removeChild(xmlFile.childNodes[i--]);
}
}
}
XML - library.xml
<?xml version="1.0" encoding="UTF-8"?>
<library>
<History>57 Volumes</History>
<Biography>78 Volumes</Biography>
<Military>104 Volumes</Military>
<SciFi>61 Volumes</SciFi>
</library>