I was reading a book and in a chapter about Controllers when it talks about rendering stuff, for JSON it has an example like this but doesn’t go in to details so I couldn’t figure out the bigger picture that this example fits in:
render :json => @projects, :include => tasks
And also some example with JSONP using it with callback functions:
render :json => @record, :callback => 'updateRecordDisplay'
Can someone explain these?
You’ll normally be returning JSON either because:
A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.
or
B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.
Or, possibly, you are eating your own dogfood and doing both
In both cases
render :json => some_datawill JSON-ify the provided data. The:callbackkey in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)Why
:callback?JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser’s built-in security. If you have your API at
api.yoursite.comand you will be serving your application off ofservices.yoursite.comyour JavaScript will not (by default) be able to makeXMLHttpRequest(XHR – aka ajax) requests fromservicestoapi. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:the server instead would send back:
Thus, a client-side JS application could create a
scripttag pointing atapi.yoursite.com/your/endpoint?name=Johnand have thevalueOfCallbackHerefunction (which would have to be defined in the client-side JS) called with the data from this other origin.)