JSON-P is a method of wrapping the JSON output of your API calls to allow other developers to call your API from within their page, bypassing the browser security mechanism.
If you peek at the HTML source of Web Connections you’ll notice we’re using JSON-P internally to provide the JS data to do the mapping. In the URL of the JSON-P call we can specify the parameter
callback or both, and this will allow others to use our JSON in their own mashups.
It also integrates nicely with the new Rails REST functionality. For example, Jeremy Keith’s profile page can also be output in JSON format by plugging ‘.js’ on the end. This is nice, but not very useful if you wanted to call it from another page.
Say Jeremy wanted to mashup this data on his own website to show who he’s friends with. He’d need some kind of JSON-P output so he can access the data from a
callback, or both
So how is this implemented behind the scenes? I have a helper function which I use throughout my application to output JSON:
class ApplicationController :js, :text => response}.merge(options)) end end
I can then use this in my
PeopleController#show action quite simply:
and that’s all there is to it. JSON-P output with Rails.