Ruby on Rails的Live搜索(过滤) [英] Ruby on Rails Live Search (Filtering)

查看:176
本文介绍了Ruby on Rails的Live搜索(过滤)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面他的Railscasts轨道AJAX教程和歌厅了一些麻烦。在现场搜索无法正常工作,我必须单击搜索按钮来获得结果。

I'm following the railscasts rails ajax tutorial and geting into some trouble. The live search does not work, I have to click the search button to get the result.

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

I have two searchfilter. First one is a select_tag. Second one is a checkbox.

下面是我的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

没有任何显示,JS控制台。

There is nothing showed in js console.

推荐答案

Mime类型

这个问题可能是你发送一个 剧本申请,当你确实需要发送一个 JSON 要求:

The problem is likely that you're sending a script request, when you really need to be sending a json request:

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

这个问题是你使用的是 的respond_to JSON (不使用 JS ),这意味着当你发送你的剧本的要求,也没有 MIME类型来提供响应

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

除了在顶部的信息,该替代的方法是执行以下操作:

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


演示

我们已经这样做过这里

我们用我们自己的JS捕捉是这样的:

We used our own JS to capture the key-ups like this:

#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

这篇关于Ruby on Rails的Live搜索(过滤)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆