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?

推荐答案

您通常会返回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(缺省情况下)将不能发出从servicesapiXMLHttpRequest(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=Johnscript标记,并具有名为with the data from this other originvalueOfCallbackHere函数(必须在客户端JS中定义)

Json相关问答推荐

使用Jolt将字符串数组转换为JSON对象数组

如何在对象投影(*)上应用滤镜投影([?port==`eth1`])?

Bash和echo命令出现意外结果

如何将加权边列表导出到JSON树?

在Vega中如何通过滑块改变条形图的宽度

JOLT转换以根据条件删除json对象

如何对未知/变量键的字典进行编码?

爆炸没有数组的 struct pyspark

如何使用jq按键 Select 并获取整个json输出来更改json中的多个值

JOLT分裂和数组数据

正向闪烁后的微调值

使用 jq 和脚本 bash 映射两个 json

如何使用 Google 表格应用程序脚本将 JSON 中的多个字段提取到 Google 表格中

JOLT 在 struct 体中间添加一个 JSON 字段

JOLT 转换 - 删除 JSON 数组中的空 node

Jackson Scala 模块的小例子?

Spring Security 和 JSON 身份验证

有什么方法可以在 elasticsearch 服务器中导入 json 文件(包含 100 个文档).?

使用 jq 如何用其他名称替换键的名称

使用 C# 调用 json