Reputation: 1
Hey guys, I've looked around online and on here a fair amount in order to try and figure out what the problem with this is. I am a newbie to anything not html, and I can not figure out why this XML is not loading.
Say I just have two files, "/contact.xml" and "/xmltest.html" and I want to load the xml into the html page using javascript. Here is what I have so far.
<html>
<body>
<h1>Carney Contacts Test</h1>
<b>Name:</b> <span id="name"></span><br />
<b>Email:</b> <span id="email"></span><br />
<b>Phone:</b> <span id="number"></span>
<script type="text/javascript">
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","contacts.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("email").innerHTML=
xmlDoc.getElementsByTagName("email")[0].childNodes[0].nodeValue;
document.getElementById("phone").innerHTML=
xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
</script>
</body>
Much of this was directly off the w3c site, and I still can not get it to work! Chrome is giving me "Uncaught TypeError: Cannot call method 'getElementsByTagName' of null", if that helps anyone.
Help appreciated!
Upvotes: 0
Views: 5532
Reputation: 536379
How are you serving contacts.xml
? Check it gets an appropriate Content-Type
for XML, eg text/xml
.
If you aren't serving contacts.xml
at all, but just accessing it from the file system, well, that's your problem. Some browsers (Chrome, IE with native XMLHttpRequest) don't allow a web page on the filesystem to read other documents from the filesystem, as it's a clear security risk. Open up the JS console in Chrome's developer tools and you'll see the explanatory error:
XMLHttpRequest cannot load file:///.../contacts.xml. Cross origin requests are only supported for HTTP.
Chuck your files on a local web server and it should work fine.
Upvotes: 0
Reputation: 6629
You missed the next part on the site (I suppose by "w3c" you mean w3schools.com):
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
The XML text needs to be loaded into a DOM parser; in your above code, xmlDoc
is just an arbitrary variable without any DOM parsing abilities.
But I guess the first problem is that you're maybe just opening the HTML file via the local file system - in that case your XML document will never be loaded, because an XMLHttpRequest
only works via HTTP; it can only load stuff from a web server, not from the file system (which is why the responseXML is null, as the browser reports).
Upvotes: 1