2013-02-11 48 views
3

我有一個評論框讓用戶按回車發表評論。它使用AJAX(jQuery)請求執行此操作。如果在事件發生之前的5秒鐘之內發佈消息,是否有一種不讓事件觸發的好方法?或者應該這樣處理服務器端?如果AJAX請求在前一個請求的5秒鐘之內,我該如何防止它?

+1

你可以使用setTimeout()。如果你想要更具體的東西,你必須告訴我們你的代碼和你已經嘗試過的東西。 – 2013-02-11 14:01:54

回答

1

這應該是definitelly也處理在服務器上,因爲javascript限制可以繞過。但是,JavaScript解決方案可以節省一些流量和時間:

var last_req = 0; 
var limit = 5000; //miliseconds 
function send_comment() { 
    var time = new Date().getTime(); 
    if(time-last_req<limit) { 
    alert("Wait please"); 
    return false; 
    } 
    last_req = time; 
    $.get("comment.php", {/*data*/}, function() {}); 
} 
5

根據您的使用情況,你可以使用throttledebounce

http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/

或者看看這篇文章:

https://stackoverflow.com/a/8056049/190596

+1

或者他也可以在5秒內停用一個按鈕。如果沒有按鈕, – dfsq 2013-02-11 14:16:12

+0

@dfsq不起作用。就像我的情況一樣。 – Loolooii 2013-02-11 14:18:27

+1

@Loolooii這就是爲什麼我把''或'字放在前面:) – dfsq 2013-02-11 14:21:37

1

這可以簡單地用一個布爾標誌來完成...

// declare this globally at the top of your script 
var allowAjax = true; 


// this would be in some event handler (on enter keypress, for example) 
if (allowAjax) { 
    $.ajax({ 
     ... 
     ... 
    }); 
} else { 
    // show message saying to wait 
} 

allowAjax = false; 

setTimeout(function() { 
    allowAjax = true; 
}, 5000); 
1

我這樣做:

if(timerStarted){ 
    window.clearTimeout(timeout); 
} 
timerStarted = true; 
timeout = window.setTimeout(function(){ 
    timerStarted = false; 
    // ajax call 
, 5000} 
相關問題