2013-06-26 47 views
16

我使用Twitter的引導預輸入從服務器顯示的一些數據,問題是用戶鍵入一個字母鍵盤緩衝,使一個AJAX調用服務器時,當我試圖快速型2或3個字母就會使2或3 AJAX調用服務器,是否有可能作出延遲,當用戶鍵入字母僅做一個Ajax調用服務器Twitter的引導預輸入延遲

我此刻代碼:

$('#SEARCH-INPUT').typeahead({ 
          source: function (query, process) { 

           jQuery.ajax({ 
            type: "GET", 
            url: "/organisations/search", 
            data: {search_name: $("#SEARCH-INPUT").val()}, 
            beforeSend: function(){ 
             $("#SEARCH-LOADING").show(); 
            }, 
            success: function (data) { 
             organisations = []; 
             organisations_hash = {}; 
             $.each(data, function(i, item){ 
             organisations_hash[item.name.toUpperCase()] = item.id; 
             organisations.push(item.name); 

             }); 
             organisations.sort(); 

             $("#SEARCH-LOADING").addClass("hidden"); 
             process(organisations); 
            }, 
            error: function(){ alert("error");}, 
            async: false 
            }); 
          } 
          ,updater: function (item) { 
           $("#SEARCH-INPUT").val(item); 
           $("#SEARCH-BUTTON").click(); 
           return item; 
          } 
          ,items: 9 
          ,minLength: 1 
         }); 

回答

35

使用此解決方案:

(function() { 
    var timeout; 

    $('[name="fill"]').typeahead({ 
     source: function(value) { 
      if (timeout) { 
       clearTimeout(timeout); 
      } 

      timeout = setTimeout(function() { 
       alert(value); 
      }, 300); 
     } 
    }); 
})(); 

見行動:

http://jsfiddle.net/nnPVn/

setTimeout和clearTime工作正常!

+0

謝謝你,完美的作品 – Maki

+1

它有一個缺陷 - 快速,如果你有一個的minLength集,那麼當你退格通過輸入文本並清除輸入,然後超時STIL結束了射擊。我希望它不要......看到這個例子:http://jsfiddle.net/nnPVn/16/ –

+0

上面的問題不會有這個問題造成的minLength爲1(默認值)。 – MrBoolean