2011-02-17 57 views
2

我试图做一个过滤,用户会按姓氏搜索。现在我在按键上使用它,但当然这会产生太多的Ajax请求,所以我宁愿在几个按键之类的地方使用它。如何在jQuery中创建一个ajax过滤器?

我所有返回的结果为表(我有一个与它的信息生成表的局部视图)

$(function() 
    { 
     $('#LastName').keypress(function() 
     { 

      $.post('ActionMethod', { 'lastName': $(this).val() }, function (response) 
      { 
       $('#results').html(response); 
      }); 
     }); 
    }); 

任何想法如何,我应该这样做。我想逻辑将类似于自动完成,我知道他们可以设置像查询db之前有多少按键。

回答

4

我想你应该只使用超时和延时Ajax调用的执行。如果在执行之前发生按键,则重置定时器...

$(function() 
    { 
     var timer; 
     $('#LastName').keypress(function() 
     { 
      var _this = this; // we need to store the this to a variable since it will be called out of context from the timeout 
      clearTimeout(timer); 
      timer = setTimeout(function(){ 
         $.post('ActionMethod', { 'lastName': $(_this).val() }, function (response) 
         { 
          $('#results').html(response); 
         }); 
         }, 500); // delay for 500 milliseconds 
     }); 
    }); 
0

如何像...

$(function() 
{ 
    $('#LastName').keypress(function() 
    { 
     if($(this).val().length > 4) 
     { 
      $.post('ActionMethod', { 'lastName': $(this).val() }, function (response) 
      { 
       $('#results').html(response); 
      }); 
     } 
    }); 
}); 
+0

我在想那个,但是4太长了。我的意思是许多亚洲名字是2个字符(李,马等)。所以这不会真的起作用。我在想,也许当他们停止打字时会这样做。 – chobo2 2011-02-17 20:08:26

0

您可以事先预先加载名称的所有唯一值,并使用该数组。如果你没有太多的值,这可以正常工作。对于你的情况,我想,我怀疑会有成千上万的独特姓氏......

你也可以设置一个时间限制,而不是按键击次数。 (就像Gaby建议的那样)。