XMLHttpRequest无法加载,因为未经允许的来源不被Access-Control-Allow-Origin允许。

6
我正在尝试通过xhr获取一个http:// javascript文件,但是我遇到了上面提到的错误。
这是我的代码:
function getXHR() {
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

    if (is_chrome) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://api.widgets.org/widget/1.1.2/widget_api.js?autoCreate=false&log=true", true);
    xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        var s = document.createElement('script');
        s.textContent = xhr.responseText;
        (document.head||document.documentElement).appendChild(s);
        s.parentNode.removeChild(s);
        }
    }
    xhr.send();
    }
}

这只适用于Chrome浏览器,因为我想在https://中使用脚本,但Chrome会自动拦截来自http://的任何内容。我从中获取脚本的服务器不支持https://,而我需要这个脚本/有多个脚本,我不想全部复制到数据文件中。
我遇到的错误是:
XMLHttpRequest cannot load http://api.widgets.org/widget/1.1.2/widget_api.js?autoCreate=false&log=true. Origin https://mysite.com is not allowed by Access-Control-Allow-Origin.

同源策略 - epascarello
3个回答

4

直接插入<script>标签,而不是使用这个XHR包装器,然后将内容插入到一个<script>标签中。

function getScript() {
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

    if (is_chrome) {
        // generate script element and set its source
        var s = document.createElement('script');
        s.src = "http://api.widgets.org/widget/1.1.2/widget_api.js?autoCreate=false&log=true";
        // remove the script element after loading
        s.addEventListener( 'load', function(){ s.parentNode.removeChild(s); } );
        (document.head||document.documentElement).appendChild(s);
    }
}

此外,我不知道为什么你要在加载完成后尝试删除脚本元素。这不会影响该代码中创建的任何对象/方法/变量。

1
没错。如果域名不同,您无法通过XHR完成此操作。请阅读:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS - marekful
这个选项并不能完全解决我遇到的 http:// 和 https:// 的问题。(即 [blocked] https://mysite.com 上的页面从 http://api.widgets.org/widget/1.1.2/widget_api.js?autoCreate=false&log=true 加载了不安全的内容) - user11235
我不确定,但是我认为问题与HTTP与HTTPS无关,而是跨域资源的问题,无论资源是HTTP还是HTTPS都会被阻止。 - speakingcode

3
我将服务器文件的完整路径更改为短路径,如下所示。

$.post('http://example.com/pages/loadRandomImages.php',{'type':'loadRandomImages','loadingReq':'True'},function(data){

------------
----------
});

将其更改为:

$.post('/pages/loadRandomImages.php',{'type':'loadRandomImages','loadingReq':'True'},function(data){

------------
----------
});

在谷歌浏览器中表现良好。


只是想说谢谢你的回答!!我有一个XMLHttpRequest.open()语句,由于上面的跨域错误而无法工作,但通过使用相对路径,我成功地让Chrome正常工作了。非常感谢。 - AlexScript

1
浏览器会阻止向与请求页面不同的服务器发出的XHR请求,这是为了防止跨站脚本攻击而进行的安全措施。
如果只是想加载脚本,请使用
<script src="..."></script>

对于一般的XHR,如果API提供了jsonp解决方法,您可以使用它,或者请求API操作员启用CORS(跨域资源共享)。

http://developer.chrome.com/extensions/xhr.html https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS http://www.w3.org/TR/cors/ http://en.wikipedia.org/wiki/JSONP


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接