Skip to content

Instantly share code, notes, and snippets.

@shawnbot
Created October 31, 2012 20:52
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 shawnbot/3989792 to your computer and use it in GitHub Desktop.
Save shawnbot/3989792 to your computer and use it in GitHub Desktop.
A lame little JSONP implementation
var request = function(options) {
var aborted = false,
abort = function() {
aborted = true;
};
switch (options.type) {
case "jsonp":
// a very simplistic JSON-P implementation
var script = document.createElement("script"),
callback = options.jsonpCallbackName || "callback";
script.src = options.url;
script.async = true;
script.className = "eddy-jsonp";
script.onerror = function() {
cleanup();
if (options.error) options.error.apply(null, arguments);
};
function cleanup() {
if (script.parentNode) script.parentNode.removeChild(script);
if (callback in window) delete window[callback];
}
abort = function() {
aborted = true;
cleanup();
};
window[callback] = function() {
cleanup();
if (!aborted) {
if (options.success) options.success.apply(null, arguments);
}
};
document.getElementsByTagName("script")[0].parentNode.appendChild(script);
break;
default:
throw "Unsupported request type: " + options.type;
}
return {
abort: abort
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment