2011-10-03 52 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); 
    } 
}); 

此致敬意!