轮询、Ajax 和状态回调

Polling, Ajax and Status Callback

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

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

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

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
  });
}

要解决此问题,您需要更正回调参数,因为您要在每个 statusCode 处理程序函数中覆盖它。此外,您可以通过从传递给 success 的 jqXHR 对象中检索状态代码来简化逻辑,而不必为 每个可能的 状态代码编写代码。这也将使递归更直接。试试这个:

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);
  });
}

但是 我强烈建议您不要遵循 AJAX 轮询的模式,因为它无法扩展从长远来看,造成的问题多于解决的问题。我强烈建议您为此遵循观察者模式,而不是使用 Websockets。有很多可用资源展示了如何在搜索时执行此操作。