2011-08-05 51 views
2

這是使用'onkeyup'搜索時中止創建多個請求的正確方法。 (注意:對於多個請求,我指的是爲字符串的每個單獨字符創建順序請求,例如:「Hello」創建'H','他',...'你好' - 5個不同的請求)刪除'onKeyUp'搜索的多個請求

var insideReq = false;      /* Initialise to false */ 
$('#search').keyup(function() { 
    var SearchString = $('#search').val(); 
    if((SearchString.length) >= 3) { 
     if(insideReq == true)    /* Check if somebody is inside */ 
      ajaxReq.abort();    /* If yes, then throw her out */ 
     insideReq = true;     /* Inform I am inside */ 
     var ajaxReq = $.get('search.exec.php', {q: SearchString}, function(ajaxContent) { 
      $('#container-list').html("<img src=\"img\\busy.gif\" class=\"busy-indicator\"/>"); 
      $('#container-list').fadeOut(5); 
      $('#container-list').html(ajaxContent); 
      $('#container-list').fadeIn(1500); 
      insideReq = false;   /* Work done; I am going */ 
     }); 
    } 
}); 
+0

這是我在我的搜索式輸入框上苦苦掙扎了一段時間的問題。我只是實現了你的'insideReq'的想法,它似乎在工作。感謝您的想法! – Paul

回答

1

您希望在有人STOPS打字時觸發此功能。爲300毫秒創建一個計時器。清除並重置每個按鍵上的定時器。當定時器超時時,激發您的AJAX請求。

+0

那麼我所做的並不是最好的主意?但是,定時器似乎是一個好概念! – SMP

2

它看起來不錯。很少有代碼優化技術可以讓您的代碼快速執行。

var insideReq = false;      /* Initialise to false */ 
$('#search').keyup(function() { 
    var SearchString = $('#search').val(); 
    if((SearchString.length) >= 3) { 
     if(insideReq == true)    /* Check if somebody is inside */ 
      ajaxReq.abort();    /* If yes, then throw her out */ 
     insideReq = true;     /* Inform I am inside */ 
     var ajaxReq = $.get('search.exec.php', {q: SearchString}, function(ajaxContent) { 
      $('#container-list') 
      .html("<img src=\"img\\busy.gif\" class=\"busy-indicator\"/>"); 
      .fadeOut(5); 
      .html(ajaxContent); 
      .fadeIn(1500); 
      insideReq = false;   /* Work done; I am going */ 
     }); 
    } 
});