如何在Rails3和jQuery中通过Ajax渲染部分内容 [英] How do I render partial via ajax in rails3 and jQuery
问题描述
我可以在rails 2中做这样的事情:
I could do sth like this in 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.
How do I do this in Rails3 with jQuery. So how can I replace html of my div with a partial via ajax call(link_to :remote => true) in Rails3.
我尝试过某事(在我的show_rec_horses.js.erb中):
I tried sth like (in my show_rec_horses.js.erb):
$("#interactionContainer").update("<%= escape_javascript(render("horses/recommended"))%>");
什么也没发生.我尝试了其他一些变体,但没有一个奏效.怎么了?是否应该以其他方式处理?任何答案将不胜感激.
And nothing happens. I tried some other variations but none worked. What am doing wrong? Should this be approached in some other way? Any answer would be greatly appreciated.
推荐答案
好的,让我们从控制器开始.
Okay, let's start with the controller.
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部分.
This will make sure the correct templates are being rendered for either a html request or a javascript request. If you just need to respond to a javascript request, delete the html part.
现在,假设您有一个包含以下内容的页面:
Now let's say you have a page containing the following:
<p><%= link_to 'Show Horses', show_rec_horses_path, remote: true %></p>
<div id="interactionContainer"></div>
单击该链接将向您的控制器中的show_rec_horses操作发出请求,此操作将呈现javascript文件show_rec_horses.js.erb
.
Clicking the link will make a request to the show_rec_horses action in your controller, this action will render the javascript file show_rec_horses.js.erb
.
此javascript文件应包含以下内容:
This javascript file should contain something like this:
$('#interactionContainer').html('<%=j render partial: 'horses/reccommended', locals: { rec_horses: @rec_horses } %>')
现在,您的容器将填充horses/_reccommended.html.erb
的内容,例如可能包含:
Now your container will be filled with the content of horses/_reccommended.html.erb
, which for example could contain:
<% rec_horses.all.each do |rec_horse| %>
<p><%= rec_horse.name %></p>
<% end %>
这篇关于如何在Rails3和jQuery中通过Ajax渲染部分内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!