我有一個評論框讓用戶按回車發表評論。它使用AJAX
(jQuery)請求執行此操作。如果在事件發生之前的5秒鐘之內發佈消息,是否有一種不讓事件觸發的好方法?或者應該這樣處理服務器端?如果AJAX請求在前一個請求的5秒鐘之內,我該如何防止它?
3
A
回答
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
根據您的使用情況,你可以使用throttle
或debounce
:
http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/
或者看看這篇文章:
0
這可以幫助你與你想要什麼要做:http://jeykeu.wordpress.com/2012/03/09/jquery-prevent-multiple-ajax-requests/
你將不得不稍微修改它以添加計時器並使用它來測試以查看是否有新的請求可能。
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}
相關問題
- 1. 如何防止ajax請求?
- 2. 防止RedirectToAction()如果AJAX請求
- 3. 防止多個AJAX請求
- 4. 如何防止跨域的Ajax請求?
- 5. 如何阻止Ajax請求存在另一個請求
- 6. AJAX請求保持緩存,我如何防止它?
- 7. 在發送下一個請求之前取消ajax請求? (jQuery)
- 8. 如何防止Url.RouteUrl(...)從當前請求
- 9. AngularJS:如何防止請求
- 10. 如何到達之前的ajax請求
- 11. 防止堆疊AJAX請求
- 12. 如何中止ajax請求,如果它需要一段時間?
- 13. 如何停止Ajax請求
- 14. 如果在Apache2上每秒請求的請求太多,請阻止IP
- 15. 如何在接受任何一個請求之前在現有請求之上堆疊第二個請求?
- 16. 如何延遲3秒。開始之前發送請求ajax?
- 17. 防止新的請求在jQuery中獲取先前的請求
- 18. 我應該如何延遲ajax請求?
- 19. 如果當前的請求,如果AJAX之一,如果它是一個POST一個
- 20. 如何在Ajax請求完成之前停止代碼?
- 21. JSF Ajax請求 - 如何停止Ajax請求後滾動頂部
- 22. ajax請求laravel 5
- 23. 我如何每5秒鐘請求一次頁面而不殺死電池?
- 24. 如何停止多個ajax請求?
- 25. 如何中止AJAX請求,直到它返回任何結果
- 26. 如何在處理來自請求的數據之前發送ajax請求?
- 27. 防止長請求請求超時
- 28. AJAX請求 - 如何查看請求?
- 29. 如何在scrapy中提出請求之前更改請求url?
- 30. 如何在發送用戶請求之前注入HTTP請求
你可以使用setTimeout()。如果你想要更具體的東西,你必須告訴我們你的代碼和你已經嘗試過的東西。 – 2013-02-11 14:01:54