2012-12-07 99 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