我正在尝试在JSON文件中呈现部分内容,以便我可以通过AJAX使用它。目前在我的JSON文件中我有:
<% self.formats = ["html"]%>
{
"html": "<%= raw escape_javascript(render(:partial => 'shared/mini_posts', :locals => {:type => "left"}).to_json )%>"
}
目前没有回复,但我的日志显示已呈现shared / mini_posts。
请注意,如果我尝试这样的话:
{
"html" : "test"
}
这会正确返回。
我的jQuery看起来像:
$j.ajax({
url('/thepage.json'),
dataType: 'json',
success: function(data){
console.log(data);
}
})
答案 0 :(得分:1)
在我的情况下,我在大约一天半的时间里遇到了同样的问题,在尝试了很多escape_javascript,to_json,render ... content_type等组合后,我终于实现了我想要的东西,那就是呈现一个json响应中的HTML部分。
所以在你的控制器中你有一个像
这样的动作def index
@candidatos = Candidatos::Base.paginate(page: params[:page], per_page: 3).to_a
respond_to do |format|
format.html # index.html.erb
format.json # index.json.erb
end
end
如果请求有.json,它将使用index.json.erb模板,在我的情况下,该模板类似于
<% self.formats = ["html"] %>
{
"html":<%= thumbnails_tag(@candidatos).to_json.html_safe %>
}
注意self.formats = ["html"]
是必要的,否则“view”将找不到partial,因为它将查找.json部分。更重要的是,不要使用escape_javascript,因为它会用\ t和\ n填充html。换句话说,的想法是将部分的输出传递给.to_json,然后传递给.html_safe 。
thumbnails_tag
只是我创建的一个助手,因为我在应用程序的很多部分中使用了部分,但基本上它有类似的东西
def thumbnails_tag objs
#Uncomment the line below to test when no much data available
# @listas.fill(@listas.first, 0..6)
thumb_span = 4
case @candidatos.length
when 1..3
thumb_span = 12 / @candidatos.length
else
thumb_span = 4
end
thumbs = {span: thumb_span}
render partial: 'candidatos/thumbnails', locals: {candidatos: @candidatos, thumbnail_options: thumbs }
end
最后,作为一个例子,使用这种方法,在.js资产中,您可以执行以下操作:
$.get('http://localhost:3000/candidatos.json?page=2', function(d){}, 'json')
.success(function(d){
$('#presidentes div.row-fluid .thumbnails').parent().append(d.html);
})
.error(function(event,error){
console.log(error);
})
无需在rails视图中使用\ t和\ n的gsub,也不需要在Javascript中使用JSON.parse字符串。
答案 1 :(得分:0)
你不能在部分上调用to_json
...这是ActiveRecord的一种方法。如果你想要json,那么它应该在partial中。
答案 2 :(得分:0)
您需要更改控制器。在respond_to部分中,您需要添加json渲染。像这样:
respond_to do |format|
format.json { render :json => @instancevar }
....
...
..
end
然后你可以简单地将.json添加到你的网址,你将收到格式为json的数据。您可能需要做的是取消默认情况下自动添加的JSON根目录。只需将此行添加到您的环境(development.rb,production.rb,...)配置:
config.active_record.include_root_in_json = false
解析json时这很重要。