Created
October 31, 2012 20:52
-
-
Save shawnbot/3989792 to your computer and use it in GitHub Desktop.
A lame little JSONP implementation
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
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