【问题标题】:Javascript ES6 Get JSON from URL (no jQuery)Javascript ES6 从 URL 获取 JSON(没有 jQuery)
【发布时间】:2017-11-10 03:07:09
【问题描述】:

我想知道是否有任何 ES6 方法可以从 url 获取 json 或其他数据。

jQuery GET 和 Ajax 调用很常见,但我不想在这个中使用 jQuery。

典型的调用如下所示:

var root = 'http://jsonplaceholder.typicode.com';

$.ajax({
  url: root + '/posts/1',
  method: 'GET'
}).then(function(data) {
  console.log(data);
});

或者没有 jQuery 类似这样:

function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}

我的问题是...是否有任何新的方法可以做到这一点...例如 ES6 还是还是一样?

【问题讨论】:

  • Internet Explorer 不支持fetch
  • @trincot 很多公司都使用 Internet Explorer 作为他们的主要浏览器。
  • @DamienGold 它不支持 Promises,但 OP 已将此问题标记为 ecmascript-6es6-promise
  • @DamienGold 然后使用 polyfill。

标签: javascript ecmascript-6 es6-promise


【解决方案1】:

FETCH API

例子:

// url (required), options (optional)
fetch('https://davidwalsh.name/some/url', {
    method: 'get'
}).then(function(response) {

}).catch(function(err) {
    // Error :(
});

更多信息:

https://developer.mozilla.org/en/docs/Web/API/Fetch_API

【讨论】:

    【解决方案2】:

    是的,使用新的Fetch API。使用它,您可以像执行以下操作一样压缩它:

    fetch(url).then(r => r.json())
      .then(data => console.log(data))
      .catch(e => console.log("Booo"))
    

    但是,并非所有浏览器都支持它,而且并不是每个人都对 Fetch API 实现持同样的积极态度。

    无论如何,您可以对此发表自己的看法并阅读更多内容here

    【讨论】:

      【解决方案3】:

      您想要的是Fetch API,但 Fetch API 不是 ES6 的一部分 - 它只是碰巧使用了 Promises,它在 ES6 中标准化。

      使用 Fetch API 从 URL 获取 JSON:

      window.fetch('/path/to.json')
          .then(function(response){
              return response.json();
          }).then(function(json){
              return doSomethingWith(json);
          });
      

      如果你需要支持没有 Fetch API 的浏览器,Github 已经开源了一个polyfill

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-14
        • 1970-01-01
        • 2012-05-02
        • 1970-01-01
        • 1970-01-01
        • 2012-09-09
        • 1970-01-01
        相关资源
        最近更新 更多