我正在努力实现实时搜索,但遇到了麻烦。单击搜索按钮时搜索功能正常。我通过实时搜索查看了每个堆栈问题。以下是我尝试过的两个外部链接(声誉禁止更多):
http://railscasts.com/episodes/240-search-sort-paginate-with-ajax
http://aymeric.gaurat.net/2010/how-to-develop-live-search-textbox-in-ruby-on-rails/
我的搜索功能如下所示:
index.html.erb
<%= form_tag(products_path, method: :get) do %>
<%= text_field_tag :term, params[:term] %>
<%= submit_tag 'Search', name: nil %>
<% end %>
<div id="grid-display">
<%= render "products" %>
<%= paginate @products %>
</div>
products_controller.rb
@products = Product.search(params[:term]).page(params[:page]).per(9)
product.rb
def self.search(term)
if term
where('product_name LIKE ?', "%#{term}%")
else
all
end
end
的application.js
$(function() {
$("product_search input").keyup(function() {
$.get($("#product_search").attr("action"), $("#product_search").serialize(), null, "script");
return false;
});
});
index.js.erb的
$("#products").html("<%= escape_javascript render("products") %>");
更新:
的application.js
$(document).on('turbolinks:load', (function() {
$("product_search input").keyup(function() {
$.get($("#product_search").attr("action"), $("#product_search").serialize(), null, "script");
return false;
});
}));