2012-12-07 100 views
0

我试图访问我的变量的JSON版本。我试过使用。因为我推测它现在被格式化为json对象。 @ shows.title但是导致了一个错误。 我试图使用@ shows.to_json.title来工作,但仍然不好。我想,当你format.json它已经调用to_json,这是想法使用格式或我不正确思考这种方式。如果是这样,那么格式会做什么。格式json in rails3

class ShowsController < ApplicationController 
     # GET /shows 
     # GET /shows.json 
     def index 
     @shows = Show.all 

     respond_to do |format| 
      format.html # index.html.erb 
      format.json { render json: @shows } 

     end 
     end 

index.html.erb

<p> @shows.title <p> 

我在JSON寻找结构会是这样。

[ 
       { 
        "id": "feature", 
        "width":570, 
        "title": "Lorem ipsum dolor amet emipsum do omnis iste natus", 
        "description": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantiu mdoloremque laudantium.", 
        "img": "img/work/img1.jpg", 
        "url": "http://www.bla.com" 
       }, 
       { 
        "id": "show", 
        "width":200, 
        "title": "Lorem ipsum dolo", 
        "description": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantiu mdoloremque laudantium.", 
        "img": "img/work/img2.jpg", 
        "url": "http://www.bla.com" 
       } 

]

更新:也许我没有正确地解释这一点。

我的目标是让我在控制器中的行为调用index.html页面,它现在执行。在那个页面上是一个jquery插件,它向数据库中的所有数据请求一个JSON对象。这样,它可以通过JSON解析并使用jquery插件呈现index.html页面上的所有对象。原因在于它使用了一个名为jquery.masonry.js的插件jQuery.infinitescroll.js,它现在被设置为使用多个JSON结构来创建我的页面。

+0

to_json返回一个JSON格式的字符串。 respond_to是关于发送到浏览器的输出,而不是发送到您的模板的变量的格式。这看起来像你试图将一个变量转换为json并访问html视图内部? – Seth

+0

我试图将模型的响应转换为JSON,以便我可以在模板中使用它。那么如果情况并非如此,那么格式如何呢? “输出发送到浏览器”是什么意思?我认为这是浏览器的输出使用response_to – Chapsterj

+0

我可以在我的index.html视图中为此格式化的JSON执行jquery ajax请求,然后如果respond_to输出到浏览器。 – Chapsterj

回答

0

如果你需要你的集合可以被jQuery访问,那么你可以把它作为一个json字符串在脚本块内部呈现。因此,例如在你的index.html.erb你可以把:

<%= javascript_tag "var shows = #{@shows.to_json}" %> 

这会使

<script type="type/javascript"> var shows = { "your":"json", "object":"YAY" } </script> 

但你还是想respond_to代码HTML

+0

哇这是我可以以数据库中的节目作为json获取节目的唯一方式。谢谢你。 – Chapsterj