在javascript中从localhost访问XML文件

问题描述 投票:0回答:1

我正在使用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();
        }
javascript google-chrome firefox
1个回答
1
投票

如果你想直接从磁盘运行它,你将无法使用ajax作为Chrome,可能其他浏览器不允许加载file:///网址。

您可以通过使用文件输入或拖放操作来获取文件

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

FileReader api

© www.soinside.com 2019 - 2024. All rights reserved.