【问题标题】:Live search in Rails 4 with JS and Keyup使用 JS 和 Keyup 在 Rails 4 中进行实时搜索
【发布时间】:2016-04-19 15:33:54
【问题描述】:

我有一个需要实时搜索的 Rails 应用程序(在用户输入时通过 JS/Ajax 显示结果)。这是我目前写的代码。

application.js

$(function() {
  $("#email_search input").keyup(function() {
  $.get($("#email_search").attr("action"), $("#email_search").serialize(), null, "script");
return false;
   });
 });

_email.html.erb 部分

<%= form_tag emails_path, :method => 'get', remote: true, :id => "email_search" do %>

  <%= text_field_tag :search,  params[:search], :placeholder => 'Search From, Subject, or Body, Hit Enter To Search', :class => 'form-control' %>

<% end %>

index.html.erb

<div id="emails">
  <%= render "emails" %>
</div>

<script>
  $(function() {
    setInterval(function(){
      $.getScript("/emails")
    }, 30000);
  });
</script>

index.js.erb

$("#emails").html("<%= escape_javascript render("emails") %>");

emails_controller.rb

  respond_to :html, :js
  def index
    @emails = current_user.emails.search(params[:search]).order("created_at DESC")
  end

email.rb(搜索方式)

def self.search(search)
    if search
      where('from_email ILIKE ? OR subject ILIKE ? OR body ILIKE ?', "%#{search}%", "%#{search}%", "%#{search}%")
    else
      all
    end
  end

所以这就是正在发生的事情。我可以输入1-2个字母,它会拉出结果,但之后就不会继续了,就像JS只是停顿一样。我禁用了 setInterval 计时器来轮询新消息,但它不起作用。这真的很令人沮丧,因为它适用于旧版本的 Rails,但不适用于 4.2.x 系列。

这是一个 turbolinks 问题吗?还是我需要以不同的方式编写我的 JS?我也安装了 jquery-turbolinks,但无论哪种方式都没有什么不同。

非常感谢任何帮助。

【问题讨论】:

    标签: javascript ruby ajax ruby-on-rails-4


    【解决方案1】:

    从这里的 sn-ps 很难看出,但我遇到了类似的问题,我将表单定位在索引页面的替换部分中。因此,我的表单将接受几个字符,直到 AJAX 有时间处理,然后它会用部分替换结果(包括我的表单)。它会“停滞不前”。将我的表单移到可替换区域之外修复它。

    那可能只是我的愚蠢错误;它很容易修复。但我想我会提到它。

    【讨论】:

    • 我很高兴我找到了我的旧帖子,我在 Rails 5.1.3 应用程序中遇到了类似的问题,并通过杀死正在重新渲染的搜索表单的 JS 负载来解决它失去焦点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2019-11-19
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多