Get JSON data from an URL

AJAX request using ES6 Promises

by Julien Etienne

HTML

<div id="using-fetch"></div>
<div id="using-XMLHttpRequest"></div>

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');


// Render pending state
fetch(url)
  .then(res => {
    if (res.ok) res.json().then(data => {
      // Render data on success
    });
  })
  .catch(() => /* Render error state */ )