在我的情况下,我在大约一天半的时间里遇到了同样的问题,在尝试了很多 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"] 是必需的,否则“视图”将找不到部分,因为它会查找 .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 或 Javascript 中的 JSON.parse 字符串添加 gsub。