0

I am trying to get xhr request. (The script should run in a loop every 2 seconds) This is my script:

function getJson() {
            var xhr = new XMLHttpRequest();
            xhr.open("get", "http://www.oref.org.il/WarningMessages/alerts.json", true);
            xhr.onload = function(){
                var response = JSON.parse(xhr.responseText);
                checkJson(response);
            }
            xhr.send(null);

            setTimeout(arguments.callee, 2000);
}

getJson();

I am getting this error: XMLHttpRequest cannot load http://www.oref.org.il/WarningMessages/alerts.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://klh-dev.com' is therefore not allowed access.

So I searched online and I tried to add few lines to my script but it didnt work: response.addHeader("Access-Control-Allow-Origin", "http://www.oref.org.il/WarningMessages");

response.addHeader("Access-Control-Allow-Origin", "*");

and I tried this one in external html page

header('Access-Control-Allow-Origin: *');  

Nothing worked..

user3825694
  • 59
  • 1
  • 9

1 Answers1

1

You've run into a set of issue collectively known as Cross-Origin Resource Sharing (CORS). Long story short, browsers typically don't allow scripts to access servers that the script didn't originate from, unless the server explicitly allows it. Since your script's origin http://klh-dev.com is not the same as the request target http://www.oref.org.il, the browser is blocking the request.

There are two possible solutions: 1) modify the server to implement CORS headers (probably not possible unless you are in control of the server) or 2) use JSONP to execute the request (does not work in all cases). So, JSONP or CORS?

Community
  • 1
  • 1
Mike Bell
  • 1,356
  • 11
  • 9