Last active
September 28, 2018 18:30
-
-
Save john-doherty/de9e677ddbd6b48a26e4bbfe3212b246 to your computer and use it in GitHub Desktop.
Simple, pure JavaScript HTTP Get function (IE8+, Chrome, Safari, Firefox, PhoneGap/Cordova)
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
/** | |
* GET contents of a URL | |
* @access private | |
* @param {string} url - url to get | |
* @param {function} error - function to call if there is an error | |
* @param {function} callback - function to call if success | |
* @returns {void} | |
*/ | |
function httpGet(url, error, callback) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', url); | |
xhr.withCredentials = true; | |
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
xhr.setRequestHeader('Content-Type', 'application/json'); | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState === 4) { | |
if (xhr.status === 200 || (xhr.status === 0 && xhr.responseText !== '')) { | |
callback({ | |
url: url, | |
status: 200, | |
body: xhr.responseText || '' | |
}); | |
} | |
else { | |
error({ | |
url: url, | |
status: xhr.status, | |
body: xhr.responseText || '' | |
}); | |
} | |
} | |
}; | |
xhr.send(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment