2017-06-08 83 views
1

我想知道是否有任何ES6获取json或其他网址数据的方式。Javascript ES6从URL获取JSON(没有jQuery)

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还是它仍然是一样的方式?

+2

您可能感兴趣的fetch:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch – Halcyon

+0

Internet Explorer不支持'fetch' –

+0

谁在乎互联网资源管理器? – trincot

回答

2

是有,使用新的Fetch API。使用,你可以尽可能多的compess它做这样的事情:

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

但是,它不是由所有的浏览器都支持但并没有大家同样看好提取API的实现。

无论如何,你可以创建你自己的意见,并阅读更多关于here

2

你想要什么Fetch API,但提取API 不是 ES6的一部分 - 它只是恰巧使用的承诺,这是在ES6标准化。

从与提取API的URL获取JSON:

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

如果您需要支持不具备提取API浏览器,Github上有开源了一个polyfill