2013-01-16 99 views
2

我想从一个XML文件获取数据到一个JS变量(我想使用纯JS,没有jQuery)。但我一直得到错误,同时下载文件:JavaScript - XMLHttpRequest响应状态0

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

+1

您是否在此检查了这些答案? http://stackoverflow.com/questions/2000609/jquery-ajax-status-code-0 – ripu1581

回答

1

因为它违反了相同的原产地政策。

务必:

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

谢谢你的答案。奇怪的是,浏览器本身可以发送跨域请求(例如,简单地打开url),但JS无法做到这一点。 –

+0

_DON'T_去w3schools,请不要。 [这是为什么](http://w3fools.com/)。我建议使用quirksmode或MDN来创建可靠的文档,甚至是JavaScriptKit –