Skip to content

Instantly share code, notes, and snippets.

@Radagaisus
Created March 29, 2012 21:08
Show Gist options
  • Select an option

  • Save Radagaisus/2243826 to your computer and use it in GitHub Desktop.

Select an option

Save Radagaisus/2243826 to your computer and use it in GitHub Desktop.
JSONP in 12 lines of Coffee
# 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