jQuery停止加载

时间:2015-07-05 16:04:09

标签: jquery

我制作了一个简单的实时搜索功能来过滤表格中的结果。

见下文:

$( "#searchinput" ).keyup(function() {

  if ($( "#searchinput" ).val() == ''){
    //LEEG
    $( "#tabledatadiv" ).html('Loading...');
    $( "#tabledatadiv" ).load('tabledata.php');
  }else{
    //NIET LEEG
    $( "#tabledatadiv" ).html('Loading...');
    $( "#tabledatadiv" ).load('tabledata.php?searchquery='+encodeURIComponent($( "#searchinput" ).val()));
  }

});

问题在于,当用户快速键入时,我的脚本搜索的前一个"字符串有很多结果,之前搜索的结果会覆盖最后一个搜索结果。

所以,当搜索" ax"它给出了2个结果,它首先尝试(在打字时)搜索" a"有5000个结果。

加载ax的结果比加载a的结果花费的时间少,所以你需要的时间很短,然后div的内容会被" a"的结果覆盖。

如何防止这种情况?当用户键入搜索框时,它应该停止加载或显示上一次击键的结果。

2 个答案:

答案 0 :(得分:1)

你应该真的使用jquery-ui的autocomplete api。它为您提供了很多选项(如延迟,minLength等)。

如果您需要中止之前的请求,可以使用like this

答案 1 :(得分:0)

如果问题确实是"用户输入太快"问题,您可以按设定时间延迟自动完成加载。正如Dekel指出的那样,既然你已经在使用JQuery,那么使用JQuery UI的自动完成肯定是最简单的方法,但这里有一个例子,说明你如何实现延迟而没有倾斜在JQuery UI上(如果由于某种原因你不能):

var rtime; // reference time
var inTimeoutLoop = false; // whether a subsequent keyup action is forcing the wait loop to continue
var delta = 200; // wait time between keyup actions

  $('#searchinput').keyup(function () {
    rtime = new Date();
    if (inTimeoutLoop === false) {
      inTimeoutLoop = true;
      setTimeout(keyupEnd, delta);
    }
  });

  function keyupEnd() {
    var timelapse = new Date() - rtime;
    if (timelapse < delta) {
      setTimeout(keyupEnd, delta);
    } else {
      inTimeoutLoop = false;
      doAutocomplete();
    }
  }

  function doAutocomplete() {
    if ($( "#searchinput" ).val() == ''){
      //LEEG
      $( "#tabledatadiv" ).html('Loading...');
      $( "#tabledatadiv" ).load('tabledata.php');
    }else{
      //NIET LEEG
      $( "#tabledatadiv" ).html('Loading...');
      $( "#tabledatadiv" ).load('tabledata.php?searchquery='+encodeURIComponent($( "#searchinput" ).val()));
    }
  }