簡體   English   中英

如果AJAX請求在前一個請求的5秒內,我怎么能阻止它呢?

[英]How can I prevent AJAX request if it's within 5 seconds of the previous request?

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

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

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

或者看看這篇文章:

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

這應該是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() {});
}

這可以通過布爾標志簡單地完成......

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

我會用這個:

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

這可能會幫助您做您想做的事: http//jeykeu.wordpress.com/2012/03/09/jquery-prevent-multiple-ajax-requests/

您必須稍微修改它以添加計時器並使用它來測試以查看是否有新請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM