xmlHttpRequest返回状态0

时间:2017-05-11 14:10:38

标签: javascript xmlhttprequest jsfiddle

我无法让xmlHttpRequest返回任何状态,只有0responseText始终为空。无论我打开哪个网址,都会发生这种情况。有人能告诉我我做错了吗?

var url = "http://stackoverflow.com/";
var xmlHttp = new XMLHttpRequest();
var response = document.getElementById("response");
xmlHttp.open("GET", url, true); // true for asynchronous
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
  response.innerHTML = xmlHttp.status;
};

https://jsfiddle.net/6ub7ct6j/

提前致谢

1 个答案:

答案 0 :(得分:0)

检查控制台。您正在尝试从https页面加载http资源,浏览器正在阻止它。但是,如果您尝试https://stackoverflow.com,则会收到CORS错误。

stackoverflow.com不允许通过Ajax访问:

VM94:1 XMLHttpRequest cannot load https://stackoverflow.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.jshell.net' is therefore not allowed access.