I am new to AJAX. I'm trying to write code that will extract from an XML file and then display the results. Keep getting a syntax error.
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Extract Data from an XML file</title>
<script type="text/javascript" language="javascript">
<!--The object detection code -->
var req = null;
// Is there support for native XHR object?: IE7+, Firefox, Safari, Opera
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
//create an XMLHttpRequest object
}
else if (window.ActiveXObject)
//check for Version 6
{
req = new ActiveXObject('MSXML2.XMLHTTP.6.0');
//create an ActiveX XMLHTTP component
}
if (!req)
{
req = new ActiveXObject('MSXML2.XMLHTTP');
//fallback to version 3
}
function goXml()
{
if (req)
{
//Request data to be retrieved from the server
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var xmlDoc= req.responseXML;
var musicianInfo = xmlDoc.getElementsByTagName("*");
for (i=0;i<musicianInfo.length;i++) {
document.getElementById('XmlData').innerHTML=musicianInfo[i];
}
}
else {
req = false;
}
}
}
req.open("GET", "MusicianList.xml", true);
req.send(null);
}
//-->
</script>
</head>
<body>
<p>Click the button to show the list: <input type="button" value="Display the List" onClick="goXml()"></p>
<div id="XmlData" style="border:1px solid black;height:40;width:300">
</div>
</body>
</html>
Xml file:
<?xml version="1.0" encoding="utf-8" ?>
- <musicians>
- <musician>
<name>Bruce Springsteen</name>
<genre>Rock</genre>
<hitsong>Born in the USA</hitsong>
</musician>
- <musician>
<name>B.B. King</name>
<genre>Blues</genre>
<hitsong>The Thrill Is Gone</hitsong>
</musician>
- <musician>
<name>Tim McGraw</name>
<genre>Country</genre>
<hitsong>Live Like You Were Dying</hitsong>
</musician>
- <musician>
<name>Gordon Lightfoot</name>
<genre>Folk</genre>
<hitsong>Carefree Highway</hitsong>
</musician>
- <musician>
<name>Glenn Miller</name>
<genre>Big Band</genre>
<hitsong>In The Mood</hitsong>
</musician>
</musicians>
My hangup seems to be with this piece:
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var xmlDoc= req.responseXML;
var musicianInfo = xmlDoc.getElementsByTagName("*");
for (i=0;i<musicianInfo.length;i++) {
document.getElementById('XmlData').innerHTML=musicianInfo[i];
}
My intention was to access all of the tags (name, genre, and hitsong) in the XML file. Thought that var musicianInfo = xmlDoc.getElementsByTagName("*"); would do that. Then, loop through each tag and display the result.
Why isn't it working?