[英]Why XMLHttpRequest status 0 with this link?
我正在尝试从使用 javascript 的链接中检索一些 JSON 数据。 然而,我得到状态 = 0,我不知道为什么。 这一直对我有用,但现在我得到的只是一个空洞的回应。 我可以在浏览器中正常检索数据,所以我尝试设置 UA header 没有运气。 也许我应该设置另一个 header??
这是我检索数据的方法:
function retrieveBusData(bus) {
var file = "https:....";
var xhReq = new XMLHttpRequest();
xhReq.timeout = 50000;
xhReq.ontimeout = function() { console.log("#########--- " + getsecs() + " - TIMEOUT en retrieveBusData"); };
xhReq.open("GET", file, true);
xhReq.setRequestHeader("Accept", "application/json");
xhReq.onreadystatechange = function() {
if (xhReq.status != 200) {
printbondiinfo("X");
} else {
if (xhReq.readyState == 4) {
if (xhReq.responseText)
processData(xhReq.responseText);
else
printbondiinfo("??");
}
}
}
xhReq.send(null);
}
编辑
感谢@epascarello 向我指出 CORS 问题。 确实,我可以在控制台中看到:
Access to XMLHttpRequest at 'https://jeap.rio...' from origin 'null'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header
is present on the requested resource.
我使用php
作为解决方法。 我在自己的页面中创建了一个简单的simple.php
文件,内容如下:
<?php
file_get_contents('https://<stupid file without Access-Control-Allow-Origin header>');
?>
然后我将 XMLHttpRequest 的相应XMLHttpRequest
file
行更改为
...
var file = "https://<my site>/simple.php";
var xhReq = new XMLHttpRequest();
xhReq.open("GET", file, true);
...
In this way, the javascript XMLHttpRequest
is made to a page with Access-Control-Allow-Origin
header set (through my own .htaccess
file), and php
does not care about the Access-Control-Allow-Origin
header.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.