且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery的AJAX轮询JSON响应,处理基于AJAX的结果或JSON内容

更新时间:2023-01-17 14:55:41

您可以使用一个简单的超时递归调用ajax_request。

You could use a simple timeout to recursively call ajax_request.

success: function(xhr_data) {
  console.log(xhr_data);
  if (xhr_data.status == 'pending') {
    setTimeout(function() { ajax_request(); }, 15000); // wait 15 seconds than call ajax request again
  } else {
    success(xhr_data);
  }
}

坚持围绕该行的计数器检查,你已经有了调查的最大数。

Stick a counter check around that line and you've got a max number of polls.

if (xhr_data.status == 'pending') {
  if (cnt < 6) {
    cnt++;
    setTimeout(function() { ajax_request(); }, 15000); // wait 15 seconds than call ajax request again
  }
}

您并不需要在误差函数做任何事情,除非你想放警报或什么的。一个简单的事实,它的错误将prevent成功函数被调用,并有可能引发另一轮。

You don't need to do anything in your error function unless you want to put an alert up or something. the simple fact that it error will prevent the success function from being called and possibly triggering another poll.