Created
March 29, 2012 21:08
-
-
Save Radagaisus/2243826 to your computer and use it in GitHub Desktop.
JSONP in 12 lines of Coffee
This file contains hidden or 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
| # JSONP | |
| # Usage: jsonp 'http://google.com/', (data) -> console.log data | |
| # Adapted from https://github.com/msingleton/TinyP | |
| ( ($, d) -> | |
| $.jsonp = (url, callback) -> | |
| # Create a random function name | |
| text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$_' | |
| c = (text[Math.floor(Math.random() * 54)] for i in [1..20]).join('') | |
| # Add the script | |
| s = d.createElement 'script' | |
| s.type = 'text/javascript' | |
| # FIXME: http://something.com/&callback, | |
| # user must add ? at the end of the url. | |
| s.src = "#{url}&callback=jsonp.#{c}" | |
| scr = d.getElementsByTagName('head')[0].appendChild s | |
| # Handle the callback | |
| $.jsonp[c] = (data) -> | |
| # Pass the data to the callback | |
| callback data | |
| # Clean Up | |
| delete $.jsonp[c] | |
| scr.parentNode.removeChild scr | |
| )(window, document) | |
| # NOTE: when namespacing jsonp to anything other than | |
| # window, make sure to change the src attribute: | |
| # s.src = "#{url}&callback=my.name.space.jsonp.#{c}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment