user7776690
user7776690

Reputation:

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 call would look like this:

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

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

or without jQuery something like this:

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();
}

My question is...Is there any new ways of doing this ... for example ES6 or is it still the same way?

Upvotes: 9

Views: 22857

Answers (4)

Matt Jaf
Matt Jaf

Reputation: 629

Here is another method using axios which is a Promise based HTTP client for the browser and node.js.

Installation:

npm install --save axios

or

yarn add axios

Then, in your project file:

import axios from 'axios'
const data = axios.get('/path/to/your/data.json')

Upvotes: 0

user1009387
user1009387

Reputation:

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){
        return doSomethingWith(json);
    });

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

Upvotes: 4

Remy Kabel
Remy Kabel

Reputation: 1017

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.

Upvotes: 9

Dinesh undefined
Dinesh undefined

Reputation: 5546

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

Upvotes: 15

Related Questions