derek5. 2016-10-20 20:23 采纳率: 100%
浏览 26

作为用户类型的Ajax搜索

I have a search feature that I am trying to implement. I would like the user to be able to type their "Search" and ajax fires as the user types to assist with finding their "Search".

I would like the user to be able to type their "Search" and ajax fires as the user types to assist with finding their "Search".

This is what I have; This is working but requires the user to hit search.

                    jQuery(document).ready(function($) {
                        // Let us trigger the search if the user clicks on the search button.
                        $('.btnSearch').click(function(){
                            makeAjaxRequest();
                        });
                        // Let us trigger the search if the user submit the form by an enter.
                        $('form').submit(function(e){
                                e.preventDefault();
                                makeAjaxRequest();
                            return false; 
                        });

                        function makeAjaxRequest() {
                            $.ajax({
                                url: 'searchAction.php',
                                data: {name: $('input#name').val()},
                                type: 'get',
                                success: function(response) {
                                    $('table#resultTable tbody').html(response);
                                }
                            });
                        }
                    });
  • 写回答

3条回答 默认 最新

  • 普通网友 2016-10-20 20:25
    关注

    You need to bind your function to the keyup-event of the input field.

    Adding the following line of code inside the $(document).ready()-function

    $( "#name" ).keyup(makeAjaxRequest);
    

    could do the trick for you.

    To only perform the AJAX request on a minimum length of three chars in the input field, you can change your makeAjaxRequest() function like so:

    function makeAjaxRequest() {
      if($('input#name').val().length > 2) {
        $.ajax({
          url: 'searchAction.php',
          data: {name: $('input#name').val()},
          type: 'get',
          success: function(response) {
            $('table#resultTable tbody').html(response);
          }
        });
      }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看