Skip to content

Instantly share code, notes, and snippets.

@chiehwen
Forked from rjbultitude/xhr-load-json.js
Created November 19, 2017 14:49
Show Gist options
  • Save chiehwen/7f2160de94127137a9605c40b34cd3b6 to your computer and use it in GitHub Desktop.
Save chiehwen/7f2160de94127137a9605c40b34cd3b6 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