Why doesn't this javascript code process this xml file?
I'm using this code:
<script type="text/javascript">
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","css/galerii.xml",false)
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
alert(xmlDoc.getElementsByTagName("GALERIE")[0].childNodes[0].nodeValue);
</script>
to process some xml:
<?xml version="1.0" encoding="UTF-8" ?>
<GALERIES>
<GALERIE>
info
</GALERIE>
<GALERIE>
other info
</GALERIE>
</GALERIES>
But I get nothing in the alert and shouldn't xmlhttp.open("GET","css/galerii.xml",false) have a value if it's successfu开发者_JAVA百科l ? It's undefined. There's a root node now, same result.
You have no root node (document element), which is a requirement in XML.
<?xml version="1.0" encoding="UTF-8" ?>
<GALERIES>
<GALERIE>
info
</GALERIE>
<GALERIE>
other info
</GALERIE>
</GALERIES>
You also have no onreadystatechange method for your AJAX request. When your code which reads the responeXML executes, the http request for the XML has yet to return. You need to read up on how to build AJAX requests: https://developer.mozilla.org/en/xmlhttprequest
Working example: http://jsfiddle.net/2F8q6/1/
Your JS modified to work as the example does:
<script type="text/javascript">
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open( "GET","css/galerii.xml", false );
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState === 4 && xmlhttp.status === 200 )
{
xmlDoc=xmlhttp.responseXML;
alert(xmlDoc.getElementsByTagName("GALERIE")[0].childNodes[0].nodeValue);
}
}
xmlhttp.send();
</script>
XML document may only have one root element.
You need a single root element.
<?xml version="1.0" encoding="UTF-8" ?>
<GALERIES>
<GALERIE>
info
</GALERIE>
<GALERIE>
other info
</GALERIE>
</GALERIES>
fix your xml . your xml is not valid. there is no root element in your xml. try here http://www.w3schools.com/Dom/dom_validate.asp.
精彩评论