2011-02-17 58 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建議的那樣)。