首页 > 解决方案 > 使用 chrome 自动完成时,ruby on rails 应用程序出现故障

问题描述

我有一个奇怪的错误,它挂断或使我的应用程序无法使用或冻结一分钟。

所以我有一个并排的 2 个表单,一个用于计费,一个用于运输,它有一个使用select2库的下拉列表。当用户选择此下拉菜单时,chrome 自动完成功能最多显示。它与 select2 下拉列表重叠。这是一张图片在此处输入图像描述

所以这里的问题是当用户使用该下拉菜单选择一个国家并使用 chrome 自动填充而不是 select2 下拉菜单并点击输入键时,右侧的表单会填充国家并挂断或冻结应用程序。当他们选择一个国家或州时,它也会向服务器发出一个获取请求。

我尝试的是:

1)关闭设置上的chrome自动完成功能。它没有问题。右边的表格不会更新(所以我断定它是 chrome)

2)我添加了一个html: {autocomplete: 'off'},但这不起作用我不知道为什么。

这是表格:

<%= form_for [:admin, @corporate_account], html: { autocomplete: "off" } do |f| %>
    <fieldset data-hook="new_property">

      <div class="row">
        <div class="col-md-12">
          <%= render partial: 'form', locals: { f: f } %>
        </div>
      </div>
      </div>
        <div class="col-md-12">
          <%= render partial: 'address_form', locals: { f: f } %>
        </div>
      </div>

      <div class="form-actions">
        <%= render partial: 'spree/admin/shared/new_resource_links' %>
      </div>
    </fieldset>
<% end %>

更新

我发现当我使用 chrome 自动完成按 Enter 键时,它会发送一个 GET 请求。但是随着应用程序的常规下拉,它不会,我认为chromes在按下回车键后会自动完成它发送表单。嗯嗯嗯嗯嗯

标签: ruby-on-railsvisual-glitch

解决方案


我们使用 select2 进行搜索。它使用 jQuery 并且 id 是动态添加的。我发现脚本动态附加了 ID。它不在.js文件中,它在.erb文件中。我已经.js在文件中添加了这个脚本.erb

<% content_for :head do %>
  <%= javascript_tag do %>
    $(document).ready(function(){
      $('span#<%= s_or_b %>country .select2').on('change', function() { update_state('<%= s_or_b %>'); });

      <%# bellow this comment the code that I added %>
      <%# this IDs are gnerated dynamically by select2 %>
      const countryID = $('span#<%= s_or_b %>country .select2 .select2-search input').attr('id')
      const stateID = $('span#<%= s_or_b %>state .select2 .select2-search input').attr('id')

      <%# add the type attribute search so autocomplete can be toggled on and off %>
      $(`#${countryID},#${stateID}`).attr('type', 'search')

      <%# on focus set the autocomplete attribute off %>
      $(`#${countryID},#${stateID}`).on('focus', function(){ 
        $(`#${countryID},#${stateID}`).attr('autocomplete', 'off')
       }) 

    });
  <% end %>
<% end %>

因此,当我专注于搜索输入时,Chrome 的自动完成功能不再起作用。


推荐阅读