【问题标题】:Loop the http request to the page until status code is 200 and then redirect to that page将http请求循环到页面,直到状态码为200,然后重定向到该页面
【发布时间】:2020-08-07 23:16:59
【问题描述】:

我是 js 的新手,所以我需要一个很好的建议如何解决这个任务。在我看来,它可能看起来像这样,但它肯定不能正常工作:

    while (status !== 200) { checkPage(); }
    function checkPage() {
        var xhr = new XMLHttpRequest(),
            method = "GET",
            url = link;
        xhr.open(method, url, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                status = xhr.status;
                return true;
            }
        }
        xhr.send();
    }

【问题讨论】:

  • 这能回答你的问题吗? Wait until all jQuery Ajax requests are done?
  • 为什么要向同一个端点发出多个 GET 请求?这是一个非常糟糕的主意。
  • @terrymorse OP 写道 “在我看来它可能看起来像这样......” 所以我认为它应该被视为伪代码
  • 我正在访问的页面有时会抛出204代码,我需要继续尝试直到我得到200,然后重定向到它
  • 这能回答你的问题吗? JavaScript: Asynchronous method in while loop

标签: javascript jquery ajax


【解决方案1】:

XMLHttpRequest 默认情况下是异步的(这是一个很好的做法,因为同步调用它会阻塞浏览器)。因此,来自XMLHttpRequest.send() 的响应应该异步处理。

传统上使用回调函数处理对异步函数的调用,使用如下模式:

function myCallback (response) {
  console.log('response from async function:', response);
}

function callAsyncFunction (myCallback) {
  const async = new AsyncFunction();

  async.oncompletion = function (response) {
    myCallback(response);
}

使用该模式,checkPage() 函数可以重写为在收到所需的 200 响应代码时使用回调函数:

// callback to receive the 200 response
function handle200 (response) {
  console.log('handle200 has received:', response);
}

function checkPage(callback) {
  const xhr = new XMLHttpRequest(),
    method = "GET",
    url = "http://your-target-url-here";

  // initialize a new GET request
  xhr.open(method, url, true);

  // respond to every readyState change
  xhr.onreadystatechange = function () {

    // ignore all readyStates other than "DONE"
    if (xhr.readyState !== XMLHttpRequest.DONE) { return; }

    // call the callback with status
    if (xhr.status === 200) {
      return callback(xhr.status);
    }

    // got something other than 200,
    // re-initialize and send another GET request
    xhr.open(method, url, true);
    xhr.send();
  }

  // send the initial GET request
  xhr.send();
}

// call checkPage once
checkPage(handle200);

参考资料:

【讨论】:

  • 谢谢!你的回答很有帮助!但我有一个问题,有时答案 200 来了,但重定向没有发生。可能是什么问题呢?我怀疑这是由于我正在访问的文档谷歌查看器。他很久没有得到支持了
  • 所以你得到一个 200 响应,然后更改 location.href,但新页面有时无法加载?那么服务器肯定有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
相关资源
最近更新 更多