javascript - 在 javascript 中从本地主机访问 XML 文件

标签 javascript google-chrome firefox

我正在使用 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();
        }

最佳答案

如果您只想直接从磁盘运行它,您将无法像 Chrome 一样使用 ajax,并且其他浏览器可能不允许加载 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

FileReader api

关于javascript - 在 javascript 中从本地主机访问 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52359333/

相关文章:

html - 在 HTML 中设置新的预呈现或预取的正确方法是什么?

java - 无法使用 Selenium 中的用户配置文件启动 Chrome 浏览器

firefox - Firefox Addon SDK 中 page-mod 和 context-menu 之间的通信

python - 如何使用 Python 访问 Firefox 的内部 indexedDB 文件?

html - 我怎样才能得到一个元素的位置编号?

javascript - Polymer WebComponents 数据绑定(bind) js 对象/数组

javascript 语义

javascript - 如何在不破坏现有 HTML 的情况下更改 DOM 中的所有文本?

JavaScript 函数更改属性值

javascript - 是否可以使用链接预取来为以后的 XHR 请求缓存 JSON API 响应?