2011-10-21 38 views
23

在我的網站上,我使用JavaScript/AJAX在用戶仍在輸入時進行搜索並顯示結果。AJAX:在表單字段中輸入時的搜索延遲

HTML(身體):

<form action="" method="post" accept-charset="utf-8"> 
    <p><input type="text" name="q" id="q" value="" onkeyup="doSearch(this.value)" /></p> 
</form> 

的JavaScript(頭):

function doSearch(text) { 
    // do the ajax stuff here 
    // call getResults.php?search=[text] 
} 

但是,這可能會導致很多來到服務器的請求。

因此我想通過設置延遲,以減輕服務器:

每當onkeyup事件被觸發,功能doSearch()應顯示「AJAX加載圖形」,等待2秒。只有在這2秒內不再觸發事件,結果應該從PHP文件中獲取。

有沒有辦法做到這一點?請問你能幫幫我嗎?提前致謝!

+2

從技術上講,這個問題還沒有問過,但三年; *後*。 – caw

回答

57
var delayTimer; 
function doSearch(text) { 
    clearTimeout(delayTimer); 
    delayTimer = setTimeout(function() { 
     // Do the ajax stuff 
    }, 1000); // Will do the ajax stuff after 1000 ms, or 1 s 
} 
+0

太棒了。謝謝! – user3560988

+0

謝謝。比我的簡單得多。 –

11

簡單的設置與的setTimeout()延遲調用,然後用clearTimeout()

HTML再次刪除它的每一個事件

<form action="" method="post" accept-charset="utf-8"> 
    <p><input type="text" name="q" id="q" value="" onkeyup="doDelayedSearch(this.value)" /></p> 
</form> 

的Javascript

var timeout = null; 

function doDelayedSearch(val) { 
    if (timeout) { 
    clearTimeout(timeout); 
    } 
    timeout = setTimeout(function() { 
    doSearch(val); //this is your existing function 
    }, 2000); 
} 
+0

謝謝!順便說一下,我喜歡你保持我選擇的代碼的分離和風格。讓提問者很容易地使用你的答案... – caw