loading xml with javascript
I am trying to run the sample code on W3School http://www.w3schools.com/xml/xml_to_html.asp
I copied the html+js codes and saved into a html file. I also downloaded their cd_catalog.xml and put it right beside the html file.
But when I run the html on Chrome, it shows nothing. It is also not working on IE.
Seems the problem is on the line "xmlhttp.send()", because I tried to put an alert right before it, the alert showed, but if I put the alert after that line, then it won't show up.
Anyone can help please?
<html>
<body>
<script type="text/javascript">
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome,开发者_C百科 Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","cd.xml",false);
alert("before");
xmlhttp.send();
alert("after");
xmlDoc=xmlhttp.responseXML;
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
</body>
</html>
the xml file is on http://www.w3schools.com/xml/cd_catalog.xml
This will not work if you are running the page as a local file. You need to run it through a webserver (like Apache) in order for the http client/server conversation to work. Can you verify that you are running it through a web server?
@user956159: Please give your extract file location/path in the xmlhttp.open
.
xmlhttp.open("GET","/Users/karthik/Desktop/cd_catalog.xml",false);
This is in Mac file path location, I've tested it in my system & it works fine after changing the path of the file.
you can use "File://users/karthikin/mydocuments/cd_catalog.xml"
or "File://C:/cd_catalog.xml"
If you are using windows try this in the xmlhttp.open
.
The above method to load the files locally, if you want to run through a webserver (like Apache) your code will work exactly.
精彩评论