Ruby on rails Rails在JSON中呈现部分
我试图在JSON文件中呈现一个部分,以便通过AJAX使用它。目前在我的JSON文件中,我有:Ruby on rails Rails在JSON中呈现部分,ruby-on-rails,Ruby On Rails,我试图在JSON文件中呈现一个部分,以便通过AJAX使用它。目前在我的JSON文件中,我有: <% self.formats = ["html"]%> { "html": "<%= raw escape_javascript(render(:partial => 'shared/mini_posts', :locals => {:type => "left"}).to_json )%>" } 这将正确返回 我的jQuery看起来像: $j.aja
<% self.formats = ["html"]%>
{
"html": "<%= raw escape_javascript(render(:partial => 'shared/mini_posts', :locals => {:type => "left"}).to_json )%>"
}
这将正确返回
我的jQuery看起来像:
$j.ajax({
url('/thepage.json'),
dataType: 'json',
success: function(data){
console.log(data);
}
})
您不能对部分的json调用
。。。这是ActiveRecord的一种方法。如果您想要json,那么它应该在分部中。您需要更改控制器。在响应部分中,您需要添加json呈现。像这样:
respond_to do |format|
format.json { render :json => @instancevar }
....
...
..
end
然后,您只需将.json添加到url中,就可以收到格式为json的数据。您可能需要做的是取消默认自动添加的JSON根的标记。只需将此行添加到您的环境(development.rb、production.rb等)配置中:
config.active_record.include_root_in_json = false
这在解析json时非常重要。在我的例子中,我在一天半的时间里遇到了相同的问题,在尝试了大量的escape\u javascript、to\u json、render等组合之后。。。内容类型等,我终于实现了我想要的,那就是在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 %>
}
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资产中,您可以执行以下操作:
{
"html" : "test"
}
$.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字符串添加gsub。那么有没有办法将部分返回为JSON?还是其他格式?我希望能用Ajax调用所有东西,你必须在partial内部完成。谢谢David,我会尝试一下,让你知道我是怎么做的!当我尝试此方法时,返回值为null。我想这是因为@instancevar(@index在我的例子中)是空的。