gengns ES

An entry from the gengns log, written by Génesis García Morilla · · JavaScript

Get JSON data from an URL

AJAX request using ES6 Promises with fetch and XMLHttpRequest. Notice that the url needs https because we request from https and the server should allow all origins (Access-Control-Allow-Origin: *)

Result of the demo “Get JSON data from an URL”

JavaScript

// Note: the url needs https because we request from https
// and the server should allow all origins (Access-Control-Allow-Origin: *)
let $div1_ = document.querySelector('#using-fetch');
let $div2_ = document.querySelector('#using-XMLHttpRequest');

/**
 * Get JSON data from an URL using fetch()
 */
fetch('https://httpbin.org/ip')
  .then(response => {
    if (response.ok) {
      response.json().then(data => {
        $div1_.textContent = JSON.stringify(data);
      });
    } else $div1_.textContent = 'Network response was not ok.';
  })
  .catch(error =>
    $div1_.textContent = 'Fetch error: ' + error
  );

/**
 * Get JSON data from an URL using XMLHttpRequest() and promises
 */
let getJSON = url => {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('get', url, true); // asynchronous
    xhr.responseType = 'json';
    xhr.onload = () => {
      if (xhr.status === 200) resolve(xhr.response); // then
      else reject(xhr.status); // catch
    };
    xhr.send();
  });
};

getJSON('https://httpbin.org/ip')
  .then(data => {
    $div2_.textContent = JSON.stringify(data);
  })
  .catch(status => {
    $div2_.textContent = 'Error: ' + status;
  });

HTML

<div id="using-fetch"></div>
<div id="using-XMLHttpRequest"></div>
Open in JSFiddle

Fetch is simpler and cleaner, it avoid callback hell and having to remember the complex API of XMLHttpRequest.

Tags: AJAX, fetch, HTTP, JSON, promises