首页 > 解决方案 > 在 javascript 中从 localhost 访问 XML 文件

问题描述

我正在使用 javascript 读取 XML 文件,然后将其显示在我的 html 页面中

它在 FireFox 上运行良好。

我用谷歌搜索,发现这是因为我的文件在我的硬盘中是本地的,这就是 Chrome 和 IE 不起作用的原因,Chrome 给出了这个错误

clocks.html:20 Failed to load file:///B:/Data/clocks.xml: 
Cross origin requests are only supported for protocol schemes: 
http, data, chrome, chrome-extension, https.

所以我创建了一个本地网站并在那里添加了文件

http://localhost/clocks.xml

我可以通过该链接访问该文件,但是当我clocks.xml在脚本中替换为http://localhost/clocks.xml以页面结尾时,即使在 FireFox 中也无法正常工作并从 FireFox 收到此错误

Cross-Origin Request Blocked: The Same Origin Policy disallows 
reading the remote resource at http://localhost/clocks.xml. 
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).[Learn More]

我怎样才能让它在所有浏览器中工作

我的脚本在这里

        window.onload = function() {
            getClockInformation();
        }

        function getClockInformation() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    updateClocks(this);
                }
            };
            xhttp.open("GET", "http://localhost/clocks.xml", true);
            xhttp.send();
        }

标签: javascriptgoogle-chromefirefox

解决方案


如果您只想直接从磁盘运行它,您将无法将 ajax 用作 Chrome,并且可能其他浏览器只是不允许加载file:///url。

您可以通过使用文件输入或拖放操作来获取文件来解决此问题

html

Select the clocks.xml file
<input type="file" id="xmlfile">

Javascript

var fileInput = document.querySelector("#xmlfile");
fileInput.addEventListener("change",function(e){
  var file = fileInput.files[0];
  var reader = new FileReader();
  reader.onloadend = function(){
    var data = reader.result;
    //data will now contain the xml text
    //use DOMParser to parse it
    var xmlDocument = (new DOMParser()).parseFromString(data,"application/xml");
    //then use the various element methods to get the elements you need
    //for instance if you had a <clock> element
    var clockData = xmlDocument.querySelector("clock").textContent
  };
  reader.readAsText(file);
})

否则,您将需要设置 cors 或从服务器加载 html 和 xml。

DOMParser api

文件阅读器 API


推荐阅读