I am trying to retrieve some JSON data from a link using javascript. Yet, I am getting status = 0, and I have no idea why. This always worked for me, but now I just get an empty response. I can retrieve the data normally in a browser, so I tried setting the UA header without luck. Maybe I should set another header??
This is my method to retrieve the data:
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);
}
EDIT
Thanks to @epascarello for pointing me the CORS problem. Indeed, I can see in the console:
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.
I used php
as a workaround. I created a simple simple.php
file in my own page with this content:
<?php
file_get_contents('https://<stupid file without Access-Control-Allow-Origin header>');
?>
and then I changed the corresponding javascript file
line for the XMLHttpRequest
with
...
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.