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_data
will JSON-ify the provided data. The :callback
key 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.com
and you will be serving your application off of services.yoursite.com
your JavaScript will not (by default) be able to make XMLHttpRequest
(XHR - aka ajax) requests from services
to api
. 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:
{"name": "John", "age": 45}
the server instead would send back:
valueOfCallbackHere({"name": "John", "age": 45})
Thus, a client-side JS application could create a script
tag pointing at api.yoursite.com/your/endpoint?name=John
and have the valueOfCallbackHere
function (which would have to be defined in the client-side JS) called with the data from this other origin.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…