如何在jquery中进行轮询?

时间:2016-06-13 06:52:10

标签: javascript jquery

我有一个邮政电话。结果之后我想做另一个得到CALL来检查状态。但如果状态为FINISHED,则

jQuery.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/doPostURL....,
        headers: {
            "x-csrf-token": sCsrftoken
        },
        success: function() {
        .. now I want to do the polling on the status
         jQuery.ajax({
            type: "GET",
            dataType: "json",
            url: "/getStatusUrl ,
            success: function(data, textStatus, response) {
        // to continue only if status if Finished 
            },
            error: function() {
            }
        });
    }
});

3 个答案:

答案 0 :(得分:1)

您可以尝试将ajax调用导出到函数并使用递归进行池化。

注意:您应该拥有一个最大计数器,这样就不会使用无限通话来泛滥服务器。

var max_count = 20;
var counter = 0;

function getStatus() {
  jQuery.ajax({
    type: "GET ",
    contentType: "application / json ",
    url: " / getStatusUrl,
    success: function(data, textStatus, response) {
      // to continue only if status if Finished 
      if (textStatus != "status" && ++counter < max_count) {
        getStatus();
      }
    },
    error: function() {}
  });
}

答案 1 :(得分:1)

只需在函数中设置代码:

jQuery.ajax({
    type: "POST",
    contentType: "application/json",
    url: "/doPostURL....,
    headers: {
        "x-csrf-token": sCsrftoken
    },
    success: function() {
      doPoll();
    }
});

var doPoll = function() {
  jQuery.ajax({
    type: "GET",
    contentType: "application/json",
    url: "/getStatusUrl ,
    success: function(data, textStatus, response) {
      //do stuff
      doPoll();
    },
    error: function() {
      //handle error
    }
  });
}

答案 2 :(得分:1)

$ .ajax返回延迟对象。

您可以执行以下操作。更多信息here

var doSomething = $.ajax({
  url: '/path/to/file',
  type: 'default GET (Other values: POST)',
  dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
  data: {param1: 'value1'},
})
function doneCallback(){
  // Handle exit condition here.
  doSomething();
}
function failCallback(){
  // Handle failure scenario here.
}
doSomething.then(doneCallback, failCallback)