Skip to content

Instantly share code, notes, and snippets.

@weisjohn
Created January 9, 2014 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weisjohn/8342584 to your computer and use it in GitHub Desktop.
Save weisjohn/8342584 to your computer and use it in GitHub Desktop.
a simple err-first callback function to make a GET request with jQuery, XHR, or Node.js
function get(url, cb) {
// use jQuery if you can, if not, XHR, or try to node
if (typeof $ !== "undefined" && !!$().jquery) {
$.ajax(url).then(function(data) {
cb(null, data);
}, function(j, t, e) {
cb(e);
});
} else if (typeof XMLHttpRequest !== "undefined") {
// simple XHR attempt
var xhr = new XMLHttpRequest();
xhr.onload = function() { if (xhr.response) cb(null, xhr.response); }
xhr.onerror = function(e) { cb(e); }
xhr.open('get', url, true);
xhr.send();
} else if (typeof module !== "undefined" && typeof require !== "undefined") {
// reckless module require based on protocol.. good luck
var protocol = require(url.split('://')[0]);
protocol.get(url, function(res) {
var response = "";
res.on('data', function(d) { response += d; });
res.on('end', function(d) {
response += d;
if (response) cb(null, response);
});
}).on('error', cb);
} else {
cb("No transport discovered");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment