【问题标题】:Accessing XML file from localhost in javascript在 javascript 中从 localhost 访问 XML 文件
【发布时间】:2018-09-16 23:52:29
【问题描述】:

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

它在 FireFox 上运行良好。

我google了一下,发现是因为我的文件在我的硬盘中是本地的,这就是为什么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();
        }

【问题讨论】:

  • 如何直接从磁盘加载 html 文件?即您的浏览器以file:///some/path/to/file.html 结束?您需要从同一域加载 html 文件,在您的情况下为 http://localhost。或者设置您的服务器为您的 xml 文件发送适当的 cors 标头
  • 文件clocks.xml与html页面在同一个文件夹中..
  • 是的,但是您是从 localhost url 加载 html 页面,即http://localhost/file.html
  • 不,我只是双击它打开的 html,像这样 B:\data\clocks.html
  • 是的,这会导致它检查 CORS,因为 file:/// url 被视为与 http://localhost 不同的域。从 localhost 加载它,就像你是 xml 文件一样,即 http://localhost/file.html 并且请求将起作用

标签: javascript google-chrome firefox


【解决方案1】:

如果您只想直接从磁盘运行它,您将无法将 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

FileReader api

【讨论】:

  • 我将我的 html 添加到本地域,在 Chrome 中工作但在 IE 中无效。
猜你喜欢
  • 2016-03-03
  • 1970-01-01
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 2018-06-07
  • 1970-01-01
  • 2017-01-12
相关资源
最近更新 更多