【问题标题】:xhr request Control Originxhr 请求控制源
【发布时间】:2014-09-12 10:57:42
【问题描述】:

我正在尝试获取 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: *');  

没有任何效果..

【问题讨论】:

  • @MikeBell 说的是真的。这些标头必须在服务器端设置,而不是客户端。

标签: javascript http xmlhttprequest request


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 2012-01-18
    • 2020-10-28
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2013-04-01
    • 2018-08-06
    相关资源
    最近更新 更多