我有一个评论框,可以让用户通过按enter来发表评论。它使用AJAX (jQuery)请求来完成此操作。有没有一种好的方法可以不让事件在上一条评论的5秒内触发并显示一条消息?或者这应该在服务器端处理?
发布于 2013-02-11 22:05:29
这也应该在服务器上处理,因为可以绕过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() {});
}发布于 2013-02-11 22:01:47
根据您的用例,您可以使用throttle或debounce
http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/
或者看看这篇文章:
发布于 2013-02-11 22:13:01
这可以简单地通过一个布尔标志来完成。
// 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);https://stackoverflow.com/questions/14813544
复制相似问题