简体   繁体   English

使用 jquery AJAX 进行实时搜索?

[英]Live Search With jquery AJAX?

How can I create a live search with Jquery AJAX, I used keypress or keyup event to loop query, but if I type 3 characters or more the AJAX will do 3 times or more.如何使用 Jquery AJAX 创建实时搜索,我使用 keypress 或 keyup 事件循环查询,但如果我输入 3 个或更多字符,AJAX 将执行 3 次或更多。

My form:我的表格:

<input class="keyword-search" type="text" name="s" autocomplete="off" placeholder="Where do you want to go?">

Here my AJAX:这是我的 AJAX:

<script>
  jQuery(document).ready(function(){
            (function($){
                $(".keyword-search").keypress(function(){
                    var keyword = $(this).val(); 
                     $(".search-appear").empty();
                    $.ajax({
                        type: "post",
                        url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                        data: { action: 'get_tour', keyword: keyword },
                        beforeSend: function() {$("#loading").fadeIn('slow');},
                        success: function(data) {
                            $("#loading").fadeOut('slow');
                            $(".search-appear").append(data);
                             }
                    });
                });
            })(jQuery);
        });
</script>   

And Here is my demo function:这是我的演示功能:

function get_tour()
            echo 'Do something!';
       ?>
      <?php  die(); }

And this is result when I type 3 characters: type 3 characters I type 2 chars: type 2 characters Who can help me it work 1 time no matter how many key press.这是我键入 3 个字符时的结果:键入 3 个字符我键入 2 个字符:键入 2 个字符无论按多少键,谁能帮我它工作 1 次。 Or it work fine anyway !或者它工作正常! Thanks a lot !!非常感谢 !!

Add your ajax to the ajaxFunction and this will work when a user types or pastes content into the search if the value is larger than 3.将您的 ajax 添加到 ajaxFunction,如果值大于 3,这将在用户键入或粘贴内容到搜索中时起作用。

The ajaxFunction will be somethign like this: ajaxFunction 将是这样的:

var ajaxFunction = function( data ) {
    $.ajax({
        type: "post",
        url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
        data: { action: 'get_tour', keyword: data },
        beforeSend: function() {$("#loading").fadeIn('slow');},
        success: function(data) {
            $("#loading").fadeOut('slow');
            $(".search-appear").append(data);
        }
    });
  }
}

 $(document).ready(function(){ var ajaxFunction = function( val ){ $('#out').text('Val: ' + val); } $('#search').on('keyup paste',function(){ if(this.value.length >= 3) ajaxFunction(this.value); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="search"> <div id="out"></div>

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

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