【问题标题】:JavaScript - XMLHttpRequest response status 0JavaScript - XMLHttpRequest 响应状态 0
【发布时间】:2012-12-30 11:14:55
【问题描述】:

我想从 XML 文件获取数据到 JS 变量(我想使用纯 JS,不使用 jQuery)。但是我在下载文件时总是出错:

var url = "http://www.w3schools.com/xml/note.xml";

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function(event){ processRequest(event,xmlhttp); };
xmlhttp.send();

function processRequest(event,xmlhttp) {
    if(xmlhttp.readyState != 4) return;
    alert("status: " +xmlhttp.status);
}

响应 xml 始终为空 - 响应状态为 0。

【问题讨论】:

标签: javascript xmlhttprequest


【解决方案1】:

尝试本地网址。你的代码不匹配same origin policy

附言w3schools 不是你想学习的地方,mdn 和 dochub.io ;)

【讨论】:

    【解决方案2】:

    因为它违反了同源政策。

    做:

    1. 转到 w3School 网站。
    2. 打开开发者控制台。
    3. 粘贴并运行您的代码,您将得到结果

    【讨论】:

    • 感谢您的回答。奇怪的是浏览器本身可以发送跨域请求(例如简单的打开url),但是JS却做不到。
    • 不要去 w3schools,拜托,不要。 here's why。我会推荐 quirksmode 或 MDN 以获得良好、可靠的文档……甚至是 JavaScriptKit
    猜你喜欢
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多