Created
January 9, 2014 21:42
-
-
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
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
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