gpt4 book ai didi

javascript - Rails 只渲染部分负载

转载 作者:行者123 更新时间:2023-11-29 22:08:39 26 4
gpt4 key购买 nike

我想在点击链接后重新加载页面的一部分。假设我想实现一个点击计数器。这是我所做的。

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

结果它用部分替换了整个页面。怎么了?

编辑一个

如 Anchor 所说,将 remote: true 添加到 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

现在尝试单击链接:我的页面没有任何反应。虽然在控制台中:

Processing by FilesController#download as JS Parameters: {"attachment"=>{"download_count"=>"175", "filename"=>"filename.doc", "id"=>"2fd9adbf6172740d46060000", "type"=>"appli"}, "user"=>"7fbceaa661727417f55e0000"} Rendered users/_downloads.html.erb (60.7ms) Completed 200 OK in 106ms (Views: 63.1ms)

我认为我现在面临一个 javascript 问题。

最佳答案

看起来您的 Controller 正在返回 HTML 响应而不是脚本响应。尝试在 link_to 中添加参数 :remote => true:

<%= link_to 'download', {controller: 'files', action: 'download', attachment: attachment, user: user}, :remote => true %>

并确保你的 Controller 在响应 block 中有相应的format.js

关于javascript - Rails 只渲染部分负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19474619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com