Javascript ES6从URL获取JSON(无jQuery)

dj2*_*017 4 javascript ecmascript-6 es6-promise

我想知道是否有任何ES6方式从网址获取json或其他数据.

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

典型的调用如下所示:

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

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

或者没有像这样的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();
}
Run Code Online (Sandbox Code Playgroud)

我的问题是......有没有新方法可以做到这一点......例如ES6还是它仍然是一样的?

Din*_*ned 10

FETCH API

例:

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

}).catch(function(err) {
    // Error :(
});
Run Code Online (Sandbox Code Playgroud)

欲获得更多信息:

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


Rem*_*bel 6

是的,使用新的Fetch API。使用它,您可以像执行以下操作一样对它进行补偿:

fetch(url).then(r => r.json())
  .then(data => console.log(data))
  .catch(e => console.log("Booo"))
Run Code Online (Sandbox Code Playgroud)

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

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