Skip to content

Instantly share code, notes, and snippets.

@krrishd
Last active August 29, 2015 14:04
Show Gist options
  • Save krrishd/f17247fcd6ff2335ca5f to your computer and use it in GitHub Desktop.
Save krrishd/f17247fcd6ff2335ca5f to your computer and use it in GitHub Desktop.
For when I don't want to use jQuery or Angular to make GET HTTP requests, neither do I care for raw XHR.
/*
* By Krish Dholakiya (itskrish.co, git.io/krish)
* MIT Licensed.
*
* GET('http://example.com/index.html', 'html') => returns DOM object
* GET('http://example.com/api.json', 'json') => returns parsed JSON object
*
* TODO: add more types (XML, etc)
* CDN url: https://cdn.rawgit.com/krrishd/f17247fcd6ff2335ca5f/raw//b5c2f93d8d3246dabe07cf9b6e73d71631f907b2
*/
window.GET = function(url, type, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send();
if(type) {
if(type == 'json') {
var jsonRes = JSON.parse(xhr.responseText);
if(callback) {
callback(jsonRes)
} else {
return jsonRes;
}
} else if(type == 'html') {
var dom = new DOMParser();
var htmlRes = dom.parseFromString(xhr.responseText, 'text/html');
if(callback) {
callback(htmlRes);
} else {
return htmlRes;
}
} else {
console.log('Type not supported, returning plaintext');
if(callback) {
callback(xhr.responseText);
} else {
return xhr.responseText;
}
}
}
if(callback) {
callback(xhr.responseText);
} else {
return xhr.responseText;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment