简体   繁体   English

Ruby on Rails实时搜索(过滤)

[英]Ruby on Rails Live Search (Filtering)

I'm following the railscasts rails ajax tutorial and geting into some trouble. 我正在关注railscasts rails ajax教程并且遇到了一些麻烦。 The live search does not work, I have to click the search button to get the result. 实时搜索不起作用,我必须单击搜索按钮才能获得结果。

I have two searchfilter. 我有两个searchfilter。 First one is a select_tag. 第一个是select_tag。 Second one is a checkbox. 第二个是复选框。

Here is my code: 这是我的代码:

results.html.erb results.html.erb

<table>
<tr>
 <td> 
 <label for="name">Filter</label></br>
   <%= form_tag artist_search_path, :id => "artists_search" do %>

      <%= select_tag :titel_id, options_from_collection_for_select(titel.all, :id, :name, params[:titel_id]), include_blank: true, class: "form-control" %>

      <input type="checkbox" name="option[]" value="1" id="1"/><label></label></br>


      <%= button_to '#', class: 'btn btn-default' do %>
      <%= t(:find) %>
      <% end %>
    <% end %>

    </td>

    <td>
  <div id="searchresult">
    <% @users.each do |user|%>
      <div>
       <div>
        <div>
         <div> <%= user.zip %> </div>
        </div>
        <div class="desc">

         </div>
<% end %>
</td>
</tr>
</table>

application.js 的application.js

  # Ajax search on keyup
  $('#artists_search input').keyup( ->
    $.get($("#artists_search").attr("action"), $("#artists_search").serialize(), null, 'script')
    false
  )

user.html.erb user.html.erb

def result
if params[:titel_id].present?
   @users = User.where('titel_id = ?', titel_id)

if params[:option].present?
   @users = User.where(..)

else
  @users = User.all
end

respond_to do |format|
  format.html  # result.html.erb
  format.json  { render :json => @users }
end

end

There is nothing showed in js console. 在js控制台中没有显示任何内容。

Mime Types 哑剧类型

The problem is likely that you're sending a script request , when you really need to be sending a json request: 当您确实需要发送json请求时,问题很可能是您正在发送script请求:

 $('#artists_search input').keyup( ->
    $.get($("#artists_search").attr("action"), $("#artists_search").serialize(), null, 'json')
    false
  )

The issue is you're using the respond_to block with json only (no js ), meaning that when you send your script request, there is no mime type to provide a response 问题是你只使用带有jsonrespond_to块(没有js ),这意味着当你发送script请求时,没有mime type来提供响应

Apart from the information at the top, the alternative will be to do the following: 除了顶部的信息,另一种方法是做以下事情:

#app/controllers/users_controller.rb
def search
   ...
   respond_to do |format|
       format.json
       format.js
       format.html
   end
end

Demo 演示

We've done this before here : 我们之前已经这样做

在此输入图像描述

We used our own JS to capture the key-ups like this: 我们使用自己的JS捕获这样的key-ups

#app/assets/javascripts/jquery/livesearch.js
// Author: Ryan Heath
// http://rpheath.com

(function($) {
  $.searchbox = {}

  $.extend(true, $.searchbox, {
    settings: {
        url: 'search',
        param: 'search',
        dom_id: '#livesearch',
        minChars: 2,
        loading_css: '#livesearch_loading',
        del_id: '#livesearch_del'
    },

    loading: function() {
        $($.searchbox.settings.loading_css).show()
    },

    idle: function() {
        $($.searchbox.settings.loading_css).hide()
    },

    start: function() {
      $.searchbox.loading()
      $(document).trigger('before.searchbox')
    },

    stop: function() {
      $.searchbox.idle()
      $(document).trigger('after.searchbox')
    },

    kill: function() {
        $($.searchbox.settings.dom_id).fadeOut(50)
        $($.searchbox.settings.dom_id).html('')
        $($.searchbox.settings.del_id).fadeOut(100)
    },

    reset: function() {
        $($.searchbox.settings.dom_id).html('')
        $($.searchbox.settings.dom_id).fadeOut(50)
        $('#SearchSearch').val('')
        $($.searchbox.settings.del_id).fadeOut(100)
    },

    process: function(terms) {

        if(/\S/.test(terms)) {
            $.ajax({
                    type: 'GET',
                    url:  $.searchbox.settings.url,
                    data: {search: terms.trim()},
                    complete: function(data) {  
                        $($.searchbox.settings.del_id).fadeIn(50)
                        $($.searchbox.settings.dom_id).html(data.responseText)

                        if (!$($.searchbox.settings.dom_id).is(':empty')) {
                            $($.searchbox.settings.dom_id).fadeIn(100)
                        }

                        $.searchbox.stop();
                    }
                });
            return false;
        }else{
            $.searchbox.kill();
        }
    }
  });



    $.fn.searchbox = function(config) {
        var settings = $.extend(true, $.searchbox.settings, config || {})

        $(document).trigger('init.searchbox')
        $.searchbox.idle()

        return this.each(function() {
            var $input = $(this)

            $input
            .keyup(function() { 
                if ($input.val() != this.previousValue) {

                    if(/\S/.test($input.val().trim()) &&  $input.val().trim().length > $.searchbox.settings.minChars){ 
                        $.searchbox.start()
                        $.searchbox.process($input.val())
                    }else{
                        $.searchbox.kill()
                    }

                    this.previousValue = $input.val()

                }
            })
        })
    }
})(jQuery);

#app/assets/javascripts/application.js
$(document).ready( function() {

    var base_url = window.location.protocol + "//" + window.location.host;

    $('#SearchSearch').searchbox({
        url: base_url + '/search/',
        param: 'search',
        dom_id: '#livesearch',
        loading_css: '#livesearch_loading'
    })      

});

This is then handled as follows: 然后按如下方式处理:

#app/controllers/products_controller.rb
def search      
    @products = Product.search(params[:search])
    respond_to do |format|
        format.js   { render :partial => "elements/livesearch", :locals => {:search => @products, :query => params[:search]} }
        format.html { render :index }
    end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM