Ragnarok 2007-11-10 01:25
[翻译]用Rails实践JSON-P的输出
[color=Red][size=6]用Rails实践JSON-P的输出[/size][/color]
[quote][color=Red]原文标题:JSON-P output with Rails
原文作者:Tim Lucas
原文地址:[url]http://www.sitepoint.com/blogs/2006/10/05/json-p-output-with-rails/[/url]
译者:Ragnarok@Ruby中文社区翻译团队
译文首发:[url]http://www.ruby-lang.org.cn/forums/viewthread.php?tid=1945&extra=page%3D1&frombbs=1[/url]
转载请保留本版权信息,违者必究![/color][/quote]
最近的[url=http://webdirections.org/]Web Directions 06[/url] 会议上,Cameron Adam和Sitepoint网站的Kevin Yank在[url=http://www.themaninblue.com/writing/perspective/2006/10/03/]Mashups和APIs的演讲[/url]中,提到了JSON-P。
JSON-P是一个包装了允许别的开发者在他们的页面里绕过浏览器的安全机制来调用你的JSON输出API的方法。
如果看一下[url=http://connections.webdirections.org/]Web Connections[/url]这个网站的HTML源码,你会发现里面使用了JSON-P来映射JS数据。在调用JSON-P里的URL我们可以指定[color=Red]variable[/color],[color=Red]callback[/color]参数,或者同时指定二个,这就使别人可以在他们自己的mashups中使用我们的JSON。
JSON-P也很好地整合了新的Rails REST功能,如[url=http://connections.webdirections.org/people/37]Jeremy Keith’s profile page[/url](译者注:”[url]http://connections.webdirections.org/people/37[/url]“)在JSON格式中可以输出为[url=http://connections.webdirections.org/people/37.js]plugging ‘.js’ on the end[/url](译者注:“[url]http://connections.webdirections.org/people/37.js[/url]”)
以‘.js’为结束的格式,这虽然好,但是如果你想从别的页面里调用就没有什么作用。
话说Jeremy想mashup一个数据到他的网站然后展示出谁是他的朋友,他需要JSON-P的某种输出,以便从[color=Red]script[/color]标签中访问的数据。
为了增加JSON-P“Padding”,就正好指定一个“Variable”参数,这个参数是用来声明你要分配给Javascript变量的名字。在这个例子中我们将[url=http://connections.webdirections.org/people/37.js?variable=personJSON]指定‘'variable = personJSON’[/url]。.注意到输出中的分别没有? 现在试着指定[color=Red]callback[/color],或者[color=Red]callback[/color]和[color=Red]variable[/color]两个参数。
这在后台是怎么实现的呢?在应用程序中我有一个功能助手(Helper Function)来输出JSON:
[code] class ApplicationController < ActionController::Base
protected
def render_json(json, options={})
callback, variable = params[:callback], params[:variable]
response = begin
if callback && variable
"var #{variable} = #{json};\n#{callback}(#{variable});"
elsif variable
"var #{variable} = #{json};"
elsif callback
"#{callback}(#{json});"
else
json
end
end
render({:content_type => :js, :text => response}.merge(options))
end
end [/code]
然后我可以在我的 [color=Red]PeopleController#show[/color] 行为中相当简单地使用这段代码:
[code] class PeopleController < ApplicationController
def show
@person = Person.find(params[:id])
respond_to do |format|
format.js { render_json @person.to_json }
end
end
end [/code]
并且这就是所有为了——用Rails实践JSON-P的输出。
[[i] 本帖最后由 Ragnarok 于 2007-11-10 01:29 编辑 [/i]]
Ragnarok 2007-11-10 01:34
感谢Drive2me的校对和教导!神会保佑你的!
drive2me 2007-11-10 09:11
[quote]原帖由 [i]Ragnarok[/i] 于 2007-11-10 01:34 发表 [url=http://ruby-lang.org.cn/forums/redirect.php?goto=findpost&pid=7513&ptid=1945][img]http://ruby-lang.org.cn/forums/images/common/back.gif[/img][/url]
感谢Drive2me的校对和教导!神会保佑你的! [/quote]
你很聪明的,只要努力,就会成功的。继续加油!:)
记住要及时总结,才能不断提高。