How to enable JSONP support in a Rails app.
I have known about JSONP for some time now but it didn’t really “click” with me until this week for some reason. Now… I think it is awesome!
So, How to enable JSONP support in a Rails app?
In a Rails controller where you want to return JSON to a callback function specified in an AJAX request, simple add a callback key and value (via param[:callback]) to the call to render json:
render :json => your_data_hash.to_json, :callback => params[:callback]
When the JSONP AJAX request is made and a callback is specified (via the ?callback= param OR the jsonpCallback option in jQuery’s $.ajax() function), Rails will now send back that JSON to the specified callback function in the DOM. Voila!
While this is sorta trivial, its a nice tool to have in the bag.
I’m always learning.