如何在 rails3 和 jQuery 中通过 ajax 呈现部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5099182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I render partial via ajax in rails3 and jQuery
提问by necker
I could do sth like this in rails 2:
我可以在 Rails 2 中做这样的事情:
def show_rec_horses
rec_horses = Horses.find(:all)
page["allHorses"].replace_html :partial => "horses/recommended", :locals =>
{:rec_horses => rec_horses}
end
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.
如何使用 jQuery 在 Rails3 中执行此操作。那么如何在 Rails3 中通过 ajax call(link_to :remote => true) 用部分替换 div 的 html。
I tried sth like (in my show_rec_horses.js.erb):
我尝试过(在我的 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.
什么也没有发生。我尝试了其他一些变体,但没有一个奏效。做错了什么?应该以其他方式解决这个问题吗?任何答案将不胜感激。
回答by Arjan
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
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.
这将确保为 html 请求或 javascript 请求呈现正确的模板。如果您只需要响应 javascript 请求,请删除 html 部分。
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>
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
.
单击该链接将向控制器中的 show_rec_horses 操作发出请求,此操作将呈现 javascript 文件show_rec_horses.js.erb
。
This javascript file should contain something like this:
这个 javascript 文件应该包含如下内容:
$('#interactionContainer').html('<%=j render partial: 'horses/reccommended', locals: { rec_horses: @rec_horses } %>')
Now your container will be filled with the content of horses/_reccommended.html.erb
, which for example could contain:
现在您的容器将填充 的内容horses/_reccommended.html.erb
,例如可能包含:
<% rec_horses.all.each do |rec_horse| %>
<p><%= rec_horse.name %></p>
<% end %>