【发布时间】:2016-02-05 09:18:39
【问题描述】:
使用 vanilla XMLHttpRequest() 对象发出 CORS 请求对我来说成功,但不使用 jQuery.get() 函数。然而$.get() 是建立在$.ajax() 之上的,而$.ajax() 是建立在浏览器的XMLHttpRequest() 对象之上的。
为什么我的 jQuery .get() 告诉我不允许跨域请求?
小提琴:https://jsfiddle.net/3pwhu05t/
jQuery()
jQuery.get( {url: 'https://www.wikidata.org/wiki/Special:EntityData/Q4231.rdf'});
// or
jQuery.get( {url: 'https://www.wikidata.org/wiki/Special:EntityData/Q4231.rdf',
crossDomain: true,
xhrFields: {
withCredentials: true
},
} );
XMLHttpRequest 代码(取自this htlm5rocks.com example)
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Make the actual CORS request.
function makeCorsRequest() {
var url = 'https://www.wikidata.org/wiki/Special:EntityData/Q4231.rdf';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var responseText = xhr.responseText;
console.log(responseText);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
makeCorsRequest();
【问题讨论】:
-
你在什么浏览器上测试过这个? jQuery 不使用
XDomainRequest处理 IE CORS 请求。 -
方法 1 工作正常(在 chrome 中),方法 2 失败,因为如果允许来源标头设置为
*,则无法使用 withCredentials。从我的角度来看,似乎正在按预期工作。 -
在控制台中输入:
jQuery.get( {url: 'https://www.wikidata.org/wiki/Special:EntityData/Q4231.rdf'}).done( function(){ console.log(arguments); });并且工作正常。 -
嗯 @KevinB @epascarello ,当我在 Chrome 本地(不是在 jsFiddle 上)使用方法 1 时,我返回
XMLHttpRequest cannot load file:///C:/Users/.../path/to/js/file/..../[object%20Object]. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. -
该错误是非常描述性的。
file不是http, data, chrome, chrome-extension, https, chrome-extension-resource之一
标签: javascript jquery ajax cors