如何通过rails3和jQuery中的ajax渲染部分内容
我可以在rails 2中这样做:
def show_rec_horses rec_horses = Horses.find(:all) page["allHorses"].replace_html :partial => "horses/recommended", :locals => {:rec_horses => rec_horses} end
我如何使用jQuery在Rails3中执行此操作。 那么如何在Rails3中用部分通过ajax调用(link_to:remote => true)替换我的div的html。
我试过(在我的show_rec_horses.js.erb中):
$("#interactionContainer").update("");
没有任何反应。 我尝试了一些其他的变化但没有工作。 怎么了? 是否应该以其他方式处理? 任何答案将不胜感激。
好的,让我们从控制器开始吧。
def show_rec_horses @rec_horses = Horses.find(:all) respond_to do |format| format.html # show_rec_horses.html.erb format.js # show_rec_horses.js.erb end end
这将确保为html请求或javascript请求呈现正确的模板。 如果您只需要回复javascript请求,请删除html部分。
现在假设您有一个包含以下内容的页面:
<%= link_to 'Show Horses', show_rec_horses_path, remote: true %>
单击该链接将向控制器中的show_rec_horses操作发出请求,此操作将呈现javascript文件show_rec_horses.js.erb
。
这个javascript文件应包含以下内容:
$('#interactionContainer').html('<%=j render partial: 'horses/reccommended', locals: { rec_horses: @rec_horses } %>')
现在你的容器将填充horses/_reccommended.html.erb
的内容,例如可以包含:
<% rec_horses.all.each do |rec_horse| %> <%= rec_horse.name %>
<% end %>