简体   繁体   English

无法通过xmlhttprequest加载本地xml文件

[英]can not load local xml file through xmlhttprequest

I am using XAMPP Apache on port 80. 我在端口80上使用XAMPP Apache。

When I try with localhost in the url I get: 当我尝试使用url localhost时,我得到:

XMLHttpRequest cannot load http://localhost/ice_escape/pokus.xml . XMLHttpRequest无法加载http://localhost/ice_escape/pokus.xml Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 对预检请求的响应未通过访问控制检查:请求的资源上不存在“ Access-Control-Allow-Origin”标头。 Origin 'null' is therefore not allowed access. 因此,不允许访问原始“空”。

and also: 并且:

Uncaught TypeError: Cannot read property '0' of null 未捕获的TypeError:无法读取null的属性“ 0”

I tried allowing CORS by adding this to httpd.conf to no avail: 我尝试通过将其添加到httpd.conf来允许CORS无效:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

Then I tried changing localhost to 127.0.0.1 . 然后我尝试将localhost更改为127.0.0.1 It removes the first error, but the other error persists. 它消除了第一个错误,但另一个错误仍然存​​在。

var url = "http://127.0.0.1/iceescape/pokus.xml";
var xmlhttp;
if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
}

if (xmlhttp) {

    xmlhttp.open("GET", url, true);
    xmlhttp.setRequestHeader('Content-Type', 'text/xml');
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            txt = xmlhttp.responseText;
            {//---- some code that parses the xml
                 var strWidth = "width";
                 var a = txt.indexOf(strWidth);
                 a += strWidth.length;
                 txt = txt.slice(a,(txt.length) );
                 var width = txt.match(/\d+/)[0];// here it says its null                    
                }
             } 
        }
    };
    xmlhttp.send();

the xml: xml:

<?xml version="1.0" encoding="UTF-8"?>
<map width = "2400" height = "1800">
    <ghost type="troll" speed="5">
        <point>
        {100,200}
        </point>
        <point>
        {350,250}
        </point>
    </ghost>

What you are trying to read with XHR is not a local file. 您尝试使用XHR读取的不是本地文件。

You have origin null (which means your HTML document is a local file , loaded via the file:// URL scheme) and you are making the Ajax result to http://localhost/ice_escape/pokus.xml which is an HTTP resource on the same computer. 您的原点为null (这意味着您的HTML文档是本地文件 ,通过file:// URL方案加载),并且您将Ajax结果转换http://localhost/ice_escape/pokus.xml ,这是HTTP资源同一台计算机。

Load your HTML document from the web server too. 也从Web服务器加载HTML文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM