【问题标题】:can not load local xml file through xmlhttprequest无法通过 xmlhttprequest 加载本地 xml 文件
【发布时间】:2015-12-17 11:09:12
【问题描述】:

我在端口 80 上使用 XAMPP Apache。

当我在url 中尝试使用localhost 时,我得到:

XMLHttpRequest 无法加载 http://localhost/ice_escape/pokus.xml。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'null'。

还有:

未捕获的类型错误:无法读取 null 的属性“0”

我尝试通过将其添加到 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"

然后我尝试将localhost 更改为127.0.0.1。它消除了第一个错误,但另一个错误仍然存​​在。

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();

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>

【问题讨论】:

    标签: javascript xml apache


    【解决方案1】:

    您尝试使用 XHR 读取的不是本地文件。

    您有来源 null(这意味着您的 HTML 文档 是一个本地 文件,通过 file:// URL 方案加载)并且您正在制作 Ajax 结果http://localhost/ice_escape/pokus.xml,这是同一台计算机上的HTTP 资源

    也从网络服务器加载您的 HTML 文档。

    【讨论】:

    • 我该怎么做?
    • 您将 HTML 文档放在 Web 根目录下的某个位置,然后在浏览器的地址栏中输入 http://localhost/something
    猜你喜欢
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 2011-11-03
    • 2012-10-28
    • 2016-08-19
    • 1970-01-01
    相关资源
    最近更新 更多