Rails“ajax:成功”多次调用
Posted
技术标签:
【中文标题】Rails“ajax:成功”多次调用【英文标题】:Rails "ajax:success" call multiple times 【发布时间】:2019-01-12 18:22:18 【问题描述】:我正在创建一个模型来显示用户的关注者和关注者列表,就像 Instagram 一样:
我的控制器:
def create
@relationship = current_user.active_relationships.new followed_id: @user.id
if @relationship.save
byebug
respond_to :js
else
error_handle
end
end
关注/取消关注按钮是一个远程 (ajax) 表单。所以处理完之后就去create.js.erb:
$(".relationship-form").on("ajax:success", function(e, data, status, xhr)
$(this).replaceWith(
'<%= link_to "Unfollow", relationship_path(@relationship), method: :delete, data: disable_with: "Loading ...", remote: true, class: "btn btn-outline-dark common-btn btn-unfollow relationship-form" %>'
)
);
我的destroy.js.erb:
$(".relationship-form").on("ajax:success", function(e, data, status, xhr)
$(this).replaceWith(
'<%= link_to "Follow", user_relationships_path(@other_user), method: :post, data: disable_with: "Loading ...", remote: true, class: "btn btn-primary common-btn btn-follow relationship-form" %>'
)
);
当我第一次点击关注user A
按钮时,它会运行1次。
问题在于,如果我在user B
上再次单击关注按钮,它会为最后一个user A
运行js,然后为user B
运行js(2 次)。如果我关注user C
,它会返回user A
、user B
和user C
等等...
这是我的按钮表单:
<% if is_following.present? %>
<%= link_to "Unfollow", relationship_path(is_following), method: :delete, data: disable_with: "Loading ...",
remote: true, class: "btn btn-outline-dark common-btn btn-unfollow relationship-form" %>
<% else %>
<%= link_to "Follow", user_relationships_path(user), method: :post, data: disable_with: "Loading ...",
remote: true, class: "btn btn-primary common-btn btn-follow relationship-form" %>
<% end %>
如果我能获得“点击”元素,那就太好了,因为我想不出一种方法来为每个关注和取消关注状态命名一个唯一的 ID。
【问题讨论】:
问题似乎不在代码的那部分,能否请您添加事件/ajax 部分? 添加你的create.js,destroy.js文件也点击事件功能 @xploshioOn 我更新了我的代码,请看一下 问题似乎是每次用户单击元素时您都在创建新事件。删除 create/destroy 上的事件部分并直接替换链接,因为在该部分上,您确定它是成功的,只需让该行替换元素而不是事件的 init。测试它,如果它解决了问题,我会创建答案 完整的部分需要在文档中准备好并在该页面的第一次加载时加载。每次发送表单时它都会运行。只需从 create/destroy js 中删除它,因为它不需要超过 1 次初始化事件 【参考方案1】:原来是我自己解决的。只是有点愚蠢和肮脏的方式。
所以在控制器处理完成后,它会转到 js.erb 文件并将结果打印到 "display: none" div 中:
$("#relationship-result").html(
'<%= link_to "Unfollow", relationship_path(@relationship), method: :delete, data: disable_with: "Loading ...", remote: true, class: "btn btn-outline-dark common-btn btn-unfollow relationship-form" %>'
)
然后在application.js
,我们在我们想要的按钮上监听事件ajax:success
。所以通过使用这种方式,我们不会得到重复的事件监听,谢谢@xploshioOn。然后抓取数据并替换:
$(document).on("ajax:success", ".relationship-form", function(e, data, status, xhr)
$(this).replaceWith($("#relationship-result").html());
)
请注意,我使用 document
是因为我在这里替换了一些 DOM。所以有点诡计和肮脏但有效:v
【讨论】:
以上是关于Rails“ajax:成功”多次调用的主要内容,如果未能解决你的问题,请参考以下文章