// 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;
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.