2011-10-03 70 views
0

我在rails 3.1項目中使用jQuery。我使用的是button_to有:遙控=>真:rails 3 jquery button_to遠程json不解碼

<%= button_to "View Examples", "#{requisition_assign_path(@req.id, category_row.id)}?show_examples=1", :remote => true, :method => 'get' %> 

這得到服務器的罰款,並在這裏進行處理:

def show 
    @assignment = Assignment.find params[:id] 
    @tag = @assignment.assignee 
    examples = [] 
    @tag.example[@tag.tag].each do |e| 
     examples << {:id => e.id} 
    end 
    @examples_json = examples.to_json 
    respond_to do |format| 
     format.js {render "assign/show.js.erb"} 
    end 
    end 

其中要求show.js.erb就好:

alert(jQuery.parseJSON("<%= @examples_json %>"); 

但在瀏覽器中,文本到達,但我無法得到它解析到原始散列數組。我錯過了什麼?

----我可能已經丟失的僅僅是使用jQuery的功能的getJSON ...

回答

1

你可以張貼日誌這一行動?我在使用內置的'remote'助手時遇到的一個問題是,他們以JS而不是JSON來請求內容。使用您當前的控制器代碼,您不會從$ .getJSON獲得任何響應(您的控制器被設置爲僅響應JS)。您可以嘗試在控制器

respond_to :html, :json 

的頂部添加respond_to代碼塊,你的行動可能看起來像

def show 
    @assignment = Assignment.find(params[:id]) 
    @tag = assignment.assignee 
    @examples = [] 
    @tag.example[@tag.tag].each do |e| 
    @examples << {:id => e.id} 
    end 
    respond_with(@examples) 
end 

什麼情況是,如果你問的JSON內容的Rails 3默認響應會自動將@examples轉換爲JSON。您可以嘗試使用通用jQuery AJAX功能

jQuery.ajax({ 
    url: $(this).attr('href'), 
    type: 'GET', 
    dataType: 'JSON', 
    success: function(data){ 
    json = jQuery.parseJSON(data.responseText); 
    console.log(json); 
    } 
}); 

此致敬意!