首页 > 解决方案 > 轮询、Ajax 和状态回调

问题描述

我想使用 jQuery 和 AJAX 不断地轮询 URL,直到我得到 200 状态代码响应。URL 指向提供文件的 REST API。理想情况下,我会得到其他状态代码,我将再次调用 URL,只有当返回 200 时,我才会离开递归并做其他事情。

对于递归,我需要保留var jsonobj.

从 ajax 调用中获取响应,我惨遭失败。我试图复制这个。早些时候我试图让 jsonobj 在 statusCode 中处理,但它没有遍历。

var jsonobj = 9189829182 // (job-id) returned from an earlier call which is not depicted here

function doPoll(jsonobj) {
  function pollQuery(p_data, state) {
    jQuery.ajax({
      headers: {
        "access-token": "67e9489669217"
      },
      type: 'GET',
      url: 'https://someurl/classifier/' + jsonobj["id"],
      crossDomain: true,
      statusCode: {
        200: function(p_data, state) {
          console.log("data available");
        },
        204: function(p_data, state) {
          console.log("processing");
        }, // this shows on console, but how do we get the state out of here?
        404: function(p_data, state) {
          console.log("resource not found / not available");
        }
      }
    })
  }

  console.log("jsonobj :" + jsonobj);

  pollQuery(function(response) {
    console.log("response :" + response); // not working
    console.log("state :" + state); // not working
  });
}

标签: jqueryajaxpolling

解决方案


To fix this you need to correct the callback argument, as you're overriding it in each of the statusCode handler functions. In addition, you can simplify the logic by retrieving the status code from the jqXHR object passed to success instead of having to write code for every possible status code. This will also make the recursion more straightforward. Try this:

function doPoll(obj) {
  function pollQuery(callback) {
    jQuery.ajax({
      headers: {
        "access-token": "67e9489669217"
      },
      type: 'GET',
      url: 'https://someurl/classifier/' + obj["id"],
      crossDomain: true,
      success: function(data, status, xhr) {
        if (xhr.status !== 200) {
          setTimeout(function() {
            pollQuery(callback); // recurse after 10 second delay
          }, 10000);
          
          // if required you can handle the messages shown for 204 and 404 states here...          
        } else {
          callback && callback(data); // 200 received, execute callback function
        }
      }
    })
  }

  pollQuery(function(response) {
    console.log("response :" + response);
  });
}

However I'd strongly suggest you do not follow the pattern of AJAX polling as it doesn't scale and, long term, causes more problems than it solves. I'd strongly suggest you follow the observer pattern for this instead by using Websockets. There are lots of resources available showing how to do this when you search.


推荐阅读