我可以在 Rails 2 中做这样的事情:
def show_rec_horses
rec_horses = Horses.find(:all)
page["allHorses"].replace_html :partial => "horses/recommended", :locals =>
{:rec_horses => rec_horses}
end
如何在 Rails3 中使用 jQuery 执行此操作。那么如何在 Rails3 中通过 ajax 调用(link_to :remote => true) 将 div 的 html 替换为部分内容。
我尝试过(在我的 show_rec_horses.js.erb 中):
$("#interactionContainer").update("<%= escape_javascript(render("horses/recommended"))%>");
什么也没发生。我尝试了其他一些变体,但没有成功。我做错了什么?应该以其他方式解决这个问题吗?任何答案将不胜感激。
最佳答案
好吧,让我们从 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 部分。
现在假设您有一个页面包含以下内容:
<p><%= link_to 'Show Horses', show_rec_horses_path, remote: true %></p>
<div id="interactionContainer"></div>
单击该链接将向 Controller 中的 show_rec_horses 操作发出请求,此操作将呈现 javascript 文件 show_rec_horses.js.erb
。
这个 javascript 文件应该包含如下内容:
$('#interactionContainer').html('<%=j render partial: 'horses/reccommended', locals: { rec_horses: @rec_horses } %>')
现在您的容器将填充 horses/_reccommished.html.erb
的内容,例如可能包含:
<% rec_horses.all.each do |rec_horse| %>
<p><%= rec_horse.name %></p>
<% end %>
关于ruby-on-rails-3 - 如何在rails3和jQuery中通过ajax渲染部分内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5099182/