【问题标题】:Native XMLHttpRequest() successfully makes CORS request but jQuery .ajax does not?本机 XMLHttpRequest() 成功发出 CORS 请求但 jQuery .ajax 没有?
【发布时间】: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


【解决方案1】:

jQuery 3.0 引入了一种使用jQuery.get 的新方法,允许您传入设置对象。这就是为什么 jsfiddle 在边缘而不是 2.1.4 上工作的原因,以及为什么在您的本地机器上它请求本地文件系统从而给您一个 cors 错误。如果你想使用jQuery.get({url: theurl})语法,你必须使用jQuery 3.x,否则你应该使用jQuery.get(theurl)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2015-12-15
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多