Skip to content

Instantly share code, notes, and snippets.

@rjbultitude
Created September 4, 2016 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rjbultitude/5dcfc2e950254993e09baf7e96f1227e to your computer and use it in GitHub Desktop.
Save rjbultitude/5dcfc2e950254993e09baf7e96f1227e to your computer and use it in GitHub Desktop.
A function that makes an XHR expecting and returning JSON. In CJS format
'use strict';
module.exports = function () {
return function(file, callback, errorCallback) {
var xhr = new XMLHttpRequest();
xhr.callback = callback;
if (xhr.overrideMimeType) {
xhr.overrideMimeType('application/json');
}
xhr.ontimeout = function() {
console.error('The request for ' + file + ' timed out.');
};
xhr.open('GET', file, true);
xhr.onload = function() {
if (this.readyState === 4) {
var thisResponseText = this.responseText;
var thisResponseJSON = JSON.parse(thisResponseText);
this.callback(thisResponseJSON);
}
};
xhr.onerror = function() {
errorCallback(xhr.statusText);
};
xhr.timeout = 200;
xhr.send(null);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment