简体   繁体   中英

How to read local xml file using javascript?

Maybe the problem is that i wrote path to my file incorrectly, i'm using Linux, do i have to write path in some different way?

<script type="text/javascript">
  function func(){
    var xmlFile = new XMLHttpRequest();
    xmlFile.open("GET", "/home/kat/course/data.xml", false);
    xmlFile.send();
    xmlDoc = xmlFile.responseXML;

    document.getElementById("result_field").value = xmlDoc;
  }
</script>

The file needs to be in the webroot. So if you have the code in /var/www and your site is 'somedomain.com/index.html' you will need to have the xml file in the same /var/www directory and access it like "GET", "somedomain.com/anotherfolder/data.xml"... You can't access server directories from JS... The javascript runs on the client side, not on the server side, so the file needs to be accessible on the website.

There could be two problems. The url must be {your_server_domain}/home/kat/course/data.xml , and the document.getElementById("result_field") must be an input/textarea to accept value attribution, otherwise, use innerHTML .

Ps: Your local server domain usually is: localhost or 127.0.0.1:80 .

JavaScript can only access files your server is serving. Unless you are serving /home/kat/course/data.xml , you're going to need to move data.xml before your JavaScript can access it. Once you move it to a location being served, it will be accessible via an XHR.

As a side note, the responseXML property of an XHR is a Document object, not a string. See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML

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