2012-11-01 20 views
-1

我想下面的事情發生:使用JSON對象範圍的

當我選擇一個選擇框,我希望它通過AJAX發送JSON對象到我的控制器像這樣:

 var encoded = $.param(data);    
     jQuery.ajax ({ 
      url: '/trips', 
      type: 'GET', 
      data: {'toSearch' : encoded}, 
      success: function (response) { 
       //succes 
       console.log(encoded); 
      } 
     }); 

並使用這些作爲我的查詢參數

respond_to :json, :html 

    def index 
    @trips = Trip.scoped 
    @trips.where("category_id = ?", params[:category_ids]) if params[:category_ids] # category_ids = array; select * from trips where category_id IN [1,3,4] 


    respond_with @trips 
    end 

我該怎麼做?什麼是序列化我的JSON對象的最佳方式是什麼?

回答

0

你可以做到以下幾點:

def index 
    @trips = Trip.scoped 
    @trips.where("category_id = ?", params[:category_ids]) if params[:category_ids] # category_ids = array; select * from trips where category_id IN [1,3,4] 

    respond_to do |format| 
    format.html # index.html.erb 
    format.xml { render :xml => @trips } 
    format.json { render :json => @trips } 
    end 
end 

那麼你應該做任何你想在JavaScript回調。

編輯

如果你只想JSON格式,你可以做到以下幾點:

render :json => @trips 

您還可以檢查Layouts and Rendering in Rails指南。

+0

非常感謝你,這解決了我的問題! –

+0

我沒有足夠的聲望來做到這一點。 –