Skip to content

Instantly share code, notes, and snippets.

@john-doherty
Last active September 28, 2018 18:30
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 john-doherty/de9e677ddbd6b48a26e4bbfe3212b246 to your computer and use it in GitHub Desktop.
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)
/**
* 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