Skip to content Skip to sidebar Skip to footer

Javascript Es6 Get Json From Url (no Jquery)

I was wondering if there's any ES6 way of getting json or other data from a url. jQuery GET and Ajax calls are very common but I don't want to use jQuery in this one. A typical cal

Solution 1:

FETCH API

Example:

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

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

For more information:

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

Solution 2:

Yes there is, using the new Fetch API. Using that you can compess it as much as doing something like:

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

However, it's not supported by all browsers yet and not everybody is equally positive about the Fetch API implementation.

Anyhow, you can create your own opinion on that and read up more on it here.

Solution 3:

What you want is the Fetch API, but the Fetch API is not a part of ES6 - it just happens to use Promises, which were standardised in ES6.

To get JSON from a URL with the Fetch API:

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

If you need to support browsers which don’t have the Fetch API, Github has open sourced a polyfill.

Post a Comment for "Javascript Es6 Get Json From Url (no Jquery)"