Created
September 4, 2016 18:25
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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