[英]How can I prevent AJAX request if it's within 5 seconds of the previous request?
I have a comment box which lets a user post comment by pressing enter. 我有一个评论框,让用户按回车发表评论。 It does this using an AJAX
(jQuery) request. 它使用AJAX
(jQuery)请求执行此操作。 Is there a nice way to not let the event fire if it's within 5 seconds of the previous comment and show a message? 如果事件在前一个评论的5秒内显示并显示消息,是否有一种不让事件触发的好方法? Or should this be handled server side? 或者这应该在服务器端处理?
Depending on your use case you could use throttle
or debounce
: 根据您的使用情况,您可以使用throttle
或debounce
:
http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/ http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/
Or have a look at this post: 或者看看这篇文章:
https://stackoverflow.com/a/8056049/190596 https://stackoverflow.com/a/8056049/190596
This should be definitelly also handled on server, because javascript restrictions can be bypassed. 这应该是definitelly也在服务器上处理,因为可以绕过javascript限制。 But, the javascript solution can save some traffic and time: 但是,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() {});
}
This can be done simply with a boolean flag... 这可以通过布尔标志简单地完成......
// 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);
I would use this : 我会用这个:
if(timerStarted){
window.clearTimeout(timeout);
}
timerStarted = true;
timeout = window.setTimeout(function(){
timerStarted = false;
// ajax call
, 5000}
This might help you with what you want to do: http://jeykeu.wordpress.com/2012/03/09/jquery-prevent-multiple-ajax-requests/ 这可能会帮助您做您想做的事: http : //jeykeu.wordpress.com/2012/03/09/jquery-prevent-multiple-ajax-requests/
You would have to modify it slightly to add a timer and use that to test to see if a new request is possible. 您必须稍微修改它以添加计时器并使用它来测试以查看是否有新请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.