-
-
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
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