简体   繁体   中英

XML Parser doesn't seem to work in my javascript

I'm trying to read my XML file from a JavaScript file.

The XML File:

<?xml version="1.0" encoding="utf-8"?>
<pct>
    <occ>
        <morphology>A</morphology>
        <morphology>B</morphology>
        <morphology>C</morphology>
    <morphology>D</morphology>
    </occ>
    <life>
        <morphology>X</morphology>
        <morphology>Y</morphology>
        <morphology>Z</morphology>
    </life>
</pct>

And here is the Javascript code snippet:

function loadDynamic(){
xmlDoc = loadXMLDoc("data.xml");
    ......
}

function loadXMLDoc(filename){
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET",filename,true);
xmlhttp.send();
return xmlhttp.responseXML;
}

Now I know my loadXMLDoc function is working because I see my XML doc in xmlhttp.responseXML when I check on Chrome Console. But my xmlDoc is always null.

I'm clueless as to where I am going wrong and any help would be greatly appreciated!

Thanks!!

I suspect that when you inspect it, you're giving the call time to complete, but when your program just runs it's returning the responseXML before the call has completed (so it's still null).

You can prevent this by turning off the asynchronous request - basically, just change your true to false:

xmlhttp.open("GET",filename,false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM