单击链接后,我想重新加载页面的一部分。假设我想实现一个点击计数器。这就是我所做的。
在show.html.erb
<div id="downloads"><%= render(partial:'downloads', locals: {user: @user}) %></div>
在_downloads.html.erb
<% user.attachments.each do |attachment| %>
<%= attachment['download_count'] %>
<br>
<%= link_to 'download', {controller: 'files', action: 'download', attachment: attachment, user: user}%>
<% end %>
在show.js.erb
$("#downloads").html("<%= escape_javascript(render('downloads', locals: {user: params[:user]})) %>")
在files_controller.rb
def download
user = User.find(params[:user])
# increasing attachment's dl count
# ...
render(:partial => 'users/downloads', locals: {user: user}, :layout => false)
end
结果,它用部分替换了整个页面。怎么了?
编辑一个
remote: true
正如 Anchor 所说,添加到 link_to 中。
<%= link_to 'download', {controller: 'files', action: 'download', attachment: attachment, user: user}, remote: true %>
在files_controller.rb
替换 render(:partial => 'users/downloads', locals: {user: user}, :layout => false)
为
respond_to do |format|
format.js { render(:partial => 'users/downloads', locals: {user: user}, :layout => false)}
end
现在尝试单击链接:我的页面上没有任何反应。虽然在控制台中:
由 FilesController#download 作为 JS 参数处理:{"attachment"=>{"download_count"=>"175", "filename"=>"filename.doc", "id"=>"2fd9adbf6172740d46060000", "type"=> "appli"}, "user"=>"7fbceaa661727417f55e0000"} 渲染 users/_downloads.html.erb (60.7ms) 在 106ms 内完成 200 OK (Views: 63.1ms)
我认为我现在面临一个javascript问题。