【发布时间】:2015-05-06 07:00:40
【问题描述】:
我花了几个小时试图从不同的域访问资源。
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ 在其他 SO 帖子中被引用指出,通过在支持 CORS 的浏览器中简单地使用 XMLHttpRequest,应该启用 CORS 策略。但是我仍然得到
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.nczonline.net/. This can be fixed by moving the resource to the same domain or enabling CORS.
在 Firefox 34 中使用它时,根据 http://caniuse.com/#feat=cors 应该就足够了。
我正在尝试来自http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ 的一个简单示例
<script type="text/javascript">
function log(msg){
var output = $('#output');
output.text(output.text() + " | " + msg);
console.log(msg);
}
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
log("'withCredentials' exist in xhr");
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
log("XDomainRequest is being used");
} else {
xhr = null;
log("xhr is null");
}
return xhr;
}
function main(){
log("Attempting to make CORS request");
var request = createCORSRequest("get", "https://www.nczonline.net/");
if (request){
request.onload = function(){
log("LOADED!");
};
request.send();
}
}
$(window).load(function(){
main();
});
</script>
我得到以下输出:
Attempting to make CORS request
'withCredentials' exist in xhr
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.nczonline.net/. This can be fixed by moving the resource to the same domain or enabling CORS.
在小提琴https://jsfiddle.net/zf8ydb9v/ 上尝试它会得到相同的结果。是否有另一个杠杆需要打开才能使用 XMLHttpRequest 使用 CORS bBesides?
【问题讨论】:
标签: javascript ajax cors