简体   繁体   中英

reading an xml file in javascript

I'm using a tutorial to read a local xml file. However, I don't get any results. The Code I'm using is:

  <!DOCTYPE html>
<html>
<body>
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></span><br>
<b>From:</b> <span id="from"></span><br>
<b>Message:</b> <span id="message"></span>
</div>

<script>
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","test.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>

</body>
</html>

[xml file[test.xml]]

    <?xml version="1.0"?>
    <movies>
<to>We're the millers</to>
<from>2012</from>
<body>2012</body>
</movies>

somebody please tell me what I'm doing wrong?

You need to deploy your two files into some http server.
Ajax call can not access for local file system because of the security issue.
after you deploy them, you should test like: http://localhost/test.html

The 2nd problem is you need to remove the xml head, otherwise they browser will treat test.xml as text not xml.

<movies>
  <to>We're the millers</to>
  <from>2012</from>
  <body>2012</body>
</movies>

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