xhr请求控制原点

时间:2014-07-21 19:53:29

标签: javascript http xmlhttprequest request

我正在尝试获取xhr请求。 (脚本应该每2秒循环运行一次) 这是我的剧本:

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();

我收到此错误: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.

所以我在线搜索,我试图在我的脚本中添加几行,但它没有用: response.addHeader("Access-Control-Allow-Origin", "http://www.oref.org.il/WarningMessages");

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

我在外部html页面尝试了这个

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

没有任何效果......

1 个答案:

答案 0 :(得分:1)

您遇到了一组统称为跨源资源共享(CORS)的问题。长话短说,浏览器通常不允许脚本访问脚本没有来自的服务器,除非服务器明确允许它。由于您的脚本的来源http://klh-dev.com与请求目标http://www.oref.org.il不同,因此浏览器会阻止该请求。

有两种可能的解决方案:1)修改服务器以实现CORS标头(除非您控制服务器,否则可能无法实现)或2)使用JSONP执行请求(在所有情况下都不起作用)。 So, JSONP or CORS?

相关问题