【问题标题】:Loading JSON works with XMLHttpRequest but not with jQuery加载 JSON 适用于 XMLHttpRequest 但不适用于 jQuery
【发布时间】:2020-10-08 13:04:19
【问题描述】:

我正在尝试从我的谷歌存储中获取 JSON 文件的内容。我可以使它与 XMLHttpRequest 一起工作,但不能与 jquery 一起工作,我不知道为什么。

这行得通:

    var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this);
    }
};
xhttp.open("GET", fileUrl, true);
xhttp.send();

但这不是:

$.getJSON(fileUrl, function(data) {
  console.log( "success", data);
});

文件存储在我的谷歌存储https://storage.googleapis.com/ 我已使用 gsutil 将 cors 设置为允许任何来源(使用通配符 *)。

只有 jquery 我才能得到 ​​p>

Access to XMLHttpRequest at 'https://storage.googleapis.com/...' from origin 'http://localhost:1234' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

如何使用 jquery 进行这项工作?因为我发现 XMLHttpRequest 解决方案非常丑陋。

【问题讨论】:

    标签: javascript jquery ajax xmlhttprequest cors


    【解决方案1】:

    你试过fetch()吗?我知道它不是 jQuery,但它看起来比 XMLHttpRequest 好得多:

    // with async-await:
    (async function() {
      const response1 = await fetch('https://jsonplaceholder.typicode.com/todos/1')
      const json1 = await response1.json()
      console.log('Async-await:', json1)
    })();
    
    // with Promise:
    const response2 = fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json2 => console.log('Promise:', json2));

    【讨论】:

      猜你喜欢
      • 2021-06-22
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 2011-08-21
      相关资源
      最近更新 更多