使用ajax输入时的jQuery搜索 [英] jQuery search as you type with ajax

查看:92
本文介绍了使用ajax输入时的jQuery搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个搜索,在其中您将文本输入到文本字段中,然后onkeyup将触发一个关闭该函数的功能,该功能会将字段的值发送到页面并将结果返回到div容器.我遇到的问题是,当有人在打字时,会有一个可怕的滞后.我认为这是在尝试搜索键入的每个字母并执行每个请求.我如何做到这一点,以便如果我在框中键入内容,请等待1/2秒钟(500),如果没有键入任何内容,则进行ajax搜索,但是如果在此时间范围内又出现了另一个字母,请不要这样做甚至不关心ajax请求.我一直在努力解决这个问题,无法解决.感谢所有帮助!

i'm trying to create a search where you input text into a textfield and onkeyup it will fire a function off that will send the value of the field to a page and return the results to the div container. The problem i'm having is that when someone is typing, there is a horrible lag going on. I think what's going on is that it's trying to search each letter typed in and does each request. How do i make it so that if i type into the box, wait 1/2 a second (500), if nothing is typed in, then do the ajax search,but if in that time frame another letter comes up, don't even bother with the ajax request. I've been busting my head on this and can't figure it out. All help is appreciated!

// fired off on keyup
function findMember(s) {
    if(s.length>=3)
        $('#searchResults').load('/search.asp?s='+s);
}

推荐答案

此操作将清除每次按下的超时,因此,如果未通过1/2秒,则不会执行该功能,然后为再次500ms.就是这样,不需要加载大库.

What this will do is clear the timeout on each press, so if 1/2 second hasn't passed the func wont be executed, then set a timer for 500ms again. Thats it, no need to load a big library..

  $(document).ready(function() {

    var timeoutID = null;

    function findMember(str) {
      console.log('search: ' + str);
    }

    $('#target').keyup(function(e) {
      clearTimeout(timeoutID);
      //timeoutID = setTimeout(findMember.bind(undefined, e.target.value), 500);
      timeoutID = setTimeout(() => findMember(e.target.value), 500);
    });

  });

演示: https://jsfiddle.net/zu2L8f0o/

这篇关于使用ajax输入时的jQuery搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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