如何设置多个ajax调用的延迟并将停止按钮绑定到它们?

时间:2018-01-17 12:42:01

标签: javascript jquery ajax

我正在构建一个小应用程序来对服务器进行多次ajax调用。每个呼叫应按顺序进行,间隔为1秒。如果单击停止按钮,则应中止所有剩余的呼叫。我尝试过类似下面的代码,但无法使其工作。时间间隔不起作用,我不知道应该在哪里绑定停止按钮。

<button id="startbtn">Start!</button>
<button id="stoptbn">Stop!</button>

<script>

function makeajax(num) {
  $.ajax({
    type: "POST",
    url: "/testurl",
    data: {
       num: num
    },
    complete: function (result) {
        console.log(num);
        setTimeout(makeajax, 1000);
    } } )
};
$(document).ready(function () {
   $("#startbtn").click(function () {
      var data_array = [1, 2, 3];
      for (var i=0; i < data_array.length; i++) {
          makeajax(data_array[i]);
      };
</script>

3 个答案:

答案 0 :(得分:1)

不要使用for循环语句:

<button id="startbtn">Start!</button>
<button id="stoptbn">Stop!</button>

<script>
var xhrs = [];
function makeajax(arr) {
  if (arr !== null && arr.length > 0){
    var num = arr.shift();
    var xhr = new XMLHttpRequest();
    xhrs.push(xhr);
    $.ajax({
        type: "POST",
        url: "/testurl",
        xhr : function(){
           return xhr;
        },
        data: {
           num: num
        },
        complete: function (result) {
           if (!(xhr.readyState === 4 && xhr.status === 0)) {
             console.log(num);
             setTimeout(() => makeajax(arr), 1000);
           }
        }
    });
  }
}
$(document).ready(function () {
   $("#startbtn").click(function () {
      var data_array = [1, 2, 3];
      makeajax(data_array);
   });
   $("#stopbtn").click(function () {
      xhrs.forEach(xhr => xhr.abort());
   });
});
</script>

答案 1 :(得分:1)

一种方法是这样。如果你想停止调用下一个ajax查询,但仍然处理正在进行的查询。

var callNr = 0;
var stopId;
var data_array = [1, 2, 3];
var isStopped;
function makeajax() {
  if (!data_array.length || isStopped) { alert('no more queries'); return;}
  num = data_array.shift();
  callNr++;
  $.ajax({
    type: "POST",
    url: "/testurl",
    data: {
       num: num
    },
    complete: function (result) {
        console.log(num);
        if (!isStopped) {
            stopId = setTimeout(makeajax, 1000);
        }
        $("#response").text('Response nr:' + callNr);
    } } );
};
$(document).ready(function () {
   $("#startbtn").click(function () {
      isStopped = false;
      makeajax();
   });
   $("#stoptbn").click(function() {
       clearTimeout(stopId);
       isStopped = true;
       console.log('stopped');
   });
});

<button id="startbtn">Start!</button>
<button id="stoptbn">Stop!</button>
<button id="response">No response yet</button>

JsFiddle

答案 2 :(得分:0)

chcek this,

   function makeajax(num) {
     jqXHR = $.ajax({
        type: "POST",
        url: "/testurl",
        async : false,
        data: {
           num: num
        },
        success: function (result) {
            //Do anything you want
        },
        timeout: 3000
    };

    $("#abortAjax").click(function() { // Id of the button you want to bind 
        $(jqXHR).abort();
    });

    }