在控制器中呈现JSON [英] Rendering JSON in controller

查看:132
本文介绍了在控制器中呈现JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一本书,并且在有关控制器的一章中谈到渲染内容时,对于JSON,它有一个这样的示例,但没有详细介绍,因此我无法弄清楚该示例的大图适合:

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

还有一些将JSONP与回调函数一起使用的示例:

And also some example with JSONP using it with callback functions:

render :json => @record, :callback => 'updateRecordDisplay'

有人可以解释这些吗?

推荐答案

您通常会返回 JSON ,因为:

A)您正在将部分/全部应用程序构建为单页应用程序(SPA),并且需要客户端JavaScript能够提取其他数据而无需完全重新加载页面.

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.

B)您正在构建供第三方使用的API,并且已决定使用JSON序列化数据.

B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.

或者,也许您正在吃自己的狗粮并同时做

在两种情况下,render :json => some_data都会对提供的数据进行JSON验证.第二个示例中的:callback键需要更多说明(请参见下文),但这是同一想法的另一种变体(以JavaScript可以轻松处理的方式返回数据.)

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.)

JSONP(第二个示例)是解决相同起源政策的一种方法是每个浏览器内置安全性的一部分.如果您的API位于api.yoursite.com,并且将要从services.yoursite.com提供服务,则JavaScript(默认情况下)将无法从servicesXMLHttpRequest(XHR-aka ajax)请求>.人们绕过该限制的方式(在跨源资源共享规范之前最终)是通过从服务器发送JSON数据(就好像是JavaScript而不是JSON )来完成的.因此,而不是发回:

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}

服务器将发回邮件:

valueOfCallbackHere({"name": "John", "age": 45})

因此,客户端JS应用程序可以创建指向api.yoursite.com/your/endpoint?name=Johnscript标记,并具有名为valueOfCallbackHere函数(必须在客户端JS中定义).另一个来源的数据.)

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.)

这篇关于在控制器中呈现JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆