您通常会返回JSON,因为:
A) 您正在将应用程序的部分/全部构建为单页应用程序(SPA),并且需要客户端JavaScript能够在不完全重新加载页面的情况下拉入额外数据.
or个
B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.
或者,你可能正在吃自己的狗粮,做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(第二个示例)是绕过Same Origin Policy的一种方式,它是每个浏览器内置安全性的一部分.如果您的API是api.yoursite.com
,并且您将为services.yoursite.com
以上的应用程序提供服务,那么您的JavaScript(缺省情况下)将不能发出从services
到api
的XMLHttpRequest
(XHR-又名AJAX)请求.人们一直在偷偷绕过这一限制的方式(在Cross-Origin Resource Sharing spec was finalized之前)是通过从服务器as if it was JavaScript instead of JSON发送JSON数据).因此,与其送回:
{"name": "John", "age": 45}
the server instead would send back:
valueOfCallbackHere({"name": "John", "age": 45})
因此,客户端JS应用程序可以创建指向api.yoursite.com/your/endpoint?name=John
的script
标记,并具有名为with the data from this other origin的valueOfCallbackHere
函数(必须在客户端JS中定义)