【问题标题】:How can I prevent AJAX request if it's within 5 seconds of the previous request?如果 AJAX 请求在上一个请求的 5 秒内,我该如何阻止它?
【发布时间】:2013-03-20 19:28:37
【问题描述】:

我有一个评论框,用户可以通过按 Enter 发表评论。它使用AJAX (jQuery) 请求来执行此操作。如果事件在前一条评论的 5 秒内并显示一条消息,有没有一种很好的方法来不让事件触发?还是应该在服务器端处理?

【问题讨论】:

  • 您可以使用 setTimeout()。如果您想要更具体的内容,您必须向我们展示您的代码以及您尝试过的内容。

标签: javascript jquery events event-handling


【解决方案1】:

根据您的用例,您可以使用throttledebounce

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

或者看看这个帖子:

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

【讨论】:

  • 或者他也可以只禁用一个按钮 5 秒。
  • @dfsq 如果没有按钮则不起作用。就像我的情况一样。
  • @Loolooii 这就是为什么我把or这个词放在前面:)
【解决方案2】:

这肯定也应该在服务器上处理,因为可以绕过 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() {});
}

【讨论】:

    【解决方案3】:

    这可以简单地用一个布尔标志来完成......

    // 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);
    

    【讨论】:

      【解决方案4】:

      我会用这个:

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

      【讨论】:

        【解决方案5】:

        这可能会帮助您完成您想做的事情:http://jeykeu.wordpress.com/2012/03/09/jquery-prevent-multiple-ajax-requests/

        您必须稍微修改它以添加一个计时器并使用它来测试是否有可能发出新请求。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-12
          • 2015-09-11
          • 2019-11-04
          • 1970-01-01
          • 2017-06-08
          相关资源
          最近更新 更多