五秒后重试Ajax调用

时间:2017-04-07 00:55:43

标签: javascript jquery ajax

在这个片段中,错误的$ .ajax(this)正在进行五次ajax调用,但我需要在每个请求之间延迟5秒。请帮忙!

$.ajax({
  type: "POST",
  data: JSON.stringify(download),
  contentType: "application/json",
  url: '',
  retryCount: 1,
  retryLimit: 5,
  success: function(data) {
    $.ajax({
      type: "GET",
      url: '',
    })
        .success(function(data) {

    })
        .error(function(data) {

    })
  },
 //It has to go into error
  error : function(xhr, textStatus, errorThrown ) {
    this.retryCount++;
    if (this.retryCount <= this.retryLimit) {
      //try again
      $.ajax(this);
      return;
    } else {
      //user comes here After trying in the if loop for 5 times, with each request having five seconds delay. I am not able to keep delay between each request
    }
    return;
  }

});

2 个答案:

答案 0 :(得分:0)

试试这个:

error : function(xhr, textStatus, errorThrown ) {
    this.retryCount++;
    if (this.retryCount <= this.retryLimit) {
      //try again
      var ajaxObject = this;
      window.setTimeout(function(){
          $.ajax(ajaxObject);
      },5000);

      return;
    } else {
      //user comes here After trying in the if loop for 5 times, with each request having five seconds delay. I am not able to keep delay between each request
    }
    return;
  }

答案 1 :(得分:0)

尝试像这样包装Ajax调用:

setTimeout(function() {
    $.ajax(this);
}, 5000);