// a promise-wrapper around XHR
function request(method, url, args) {
// Creating a promise and return it
return new Promise(function (fulfill, reject) {
// Instantiates the XMLHttpRequest
var client = new XMLHttpRequest(),
data;
if (args) {
if (method === 'POST' || method === 'PUT') {
data = JSON.stringify(args);
} else {
url += '?';
var argcount = 0;
for (var key in args) {
if (args.hasOwnProperty(key)) {
if (argcount++) {
url += '&';
}
url += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
}
}
}
}
client.open(method, url);
if (data) {
client.setRequestHeader('Content-Type', 'application/json');
}
client.send(data);
client.onload = function () {
if (this.status == 200) {
// Performs the function "fulfill" when this.status is equal to 200
fulfill(this.response);
} else {
// Performs the function "reject" when this.status is different than 200
reject(new Error(this.statusText || 'Could not load'));
}
};
client.onerror = function () {
reject(new Error(this.statusText || 'Could not load'));
};
});
}
var url = 'https://developer.mozilla.org/en-US/search.json';
var args = {
'q': 'Promise'
};
// Executes the XHR call
request('GET', url, args)
// parse the response string as JSON
.then(JSON.parse)
// log the JSON
.then(function (data) {
console.log('success', data);
})
// something threw an error!
.catch(function (err) {
console.log('failure', err);
});
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.