使用 rails 每次加载后触发 javascript ajax 部分

Fire javascript ajax partial after each load using rails

我有一个菜单项触发 ajax returns javascript 部分 bootstrap 模态。我遇到的问题是当用户第一次单击菜单项时,模式会按预期打开。用户关闭模式并尝试再次打开它,它没有打开(尽管 ajax 从后端再次触发)。

考虑以下代码(使用 bootstrap 4):

Menu.html.erb:

<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
    <%= link_to user_profile_path(current_user.user_profile.id), remote: true, class: "dropdown-item" do %>
        <%= fa_icon "id-card", text: "Profile Settings" %>
    <% end %>
</div>
...
<div id="user_profile"></div>

user_profile/show.js.erb (ajax js部分):

$("#user_profile").replaceWith("<%= j render "user_profile" %>");

user_profile/_user_profile.html.erb(bootstrap 模态):

<script>
    $('#user_profile_modal').modal('show');
</script>

<%= form_with model: @user_profile do |f| %>
    <div class="modal fade" id="user_profile_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
        ...
        </div>
    </div>
<% end %>

有没有办法在每次从后端触发模态时触发 modal('show');?顺便说一句,这只是以这种方式加载到页面上的 3 个模式之一。

再次感谢!

尝试一些操作后,只需将 user_profile/show.js.erb 中的 replaceWith 替换为 html 就会导致 ajax 每次都触发。

旧:

$("#user_profile").replaceWith("<%= j render "user_profile" %>");

新:

$("#user_profile").html("<%= j render "user_profile" %>");

这是因为 replaceWith 正在替换父元素中的元素,因此不会再次触发,因为该元素已经第一次被替换。

希望对以后的人有所帮助!