Ruby on Rails实时搜索(过滤)

时间:2014-06-17 04:24:08

标签: jquery ruby-on-rails ajax ruby-on-rails-3 ruby-on-rails-4

我跟随railscasts rails ajax教程并陷入了一些麻烦。实时搜索不起作用,我必须单击搜索按钮才能获得结果。

我有两个searchfilter。第一个是select_tag。第二个是复选框。

这是我的代码:

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

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

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

js控制台中没有显示任何内容。

1 个答案:

答案 0 :(得分:4)

Mime类型

当您确实需要发送json请求时,问题很可能是您发送了script request

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

问题是您只使用respond_to阻止json阻止了(js},这意味着当您发送script请求时,没有mime type提供回复

除了顶部的信息,另一种方法是执行以下操作:

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

<强>演示

我们在here

之前完成了这项工作

enter image description here

我们使用自己的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'
    })      

});

然后按如下方式处理:

#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