在脱机时排队多个AJAX请求,在连接返回时发送

时间:2012-06-26 23:33:30

标签: javascript ajax asynchronous xmlhttprequest

我有一个AJAX密集型应用程序,需要快速或同时发送多个AJAX请求。以下代码只是一个简单的包装器,用于发送我在整个应用程序中使用的AJAX POST调用。有两个警告:

1)我希望能够在发出请求之前测试用户的互联网连接,因此如果连接断开,我可以通知他们。

2)如果他们的连接断开并继续使用应用程序,这会产生更多的AJAX调用,我想排队这些调用并在连接返回后逐个发送。

连接检查和排队工作,但是当用户重新联机时,只有部分请求被发送到服务器,并且它们似乎是从原始订单发送的。我错过了什么?为什么不发送所有请求,为什么不按顺序发送?

在任何人注意到之前,我已经看到了关于jQuery的这个主题的一些其他解决方案。我并不反对使用它们,我只想了解为什么这段代码不起作用。提前谢谢。

window.connectionState = true
window.xhrQueue = []
window.pingInterval

function xhrPost(url, packet, before, after) {
  if (!url || typeof(url) !== "string") {
    console.log("invalid url supplied in xhr call.")
    return false
  }

  var mainRequest = function() {
    var xhr= new XMLHttpRequest()

    if (typeof(after) === "function") {
      xhr.onreadystatechange = function(){
        if (xhr.readyState == 4) {
          after(xhr)
          return true
        }
      }
    }

    if (typeof(before) === "function") {
      before()
    }

    xhr.open("POST",url,true)
      if (packet) {
        xhr.send(JSON.stringify(packet))
      }
      else {
        xhr.send()
      }
  }

  ping(mainRequest)
}

function ping(mainRequest) {

  // Create pingXhr to test connection
  var pingXhr = new XMLHttpRequest()

  pingXhr.onreadystatechange = function(){
    // If pingXhr comes back successfully...
    if (pingXhr.readyState == 4) {
      if (pingXhr.status == 200) { 
        // If pingXhr comes back from being down, update user
        if (window.connectionState !== true) {
          setTimeout(function() { alert("And we're back! Your connection seems to be working now. Keep editing.") }, 1)
        }
        // If there are requests waiting, send them in order, then remove them
        if (window.xhrQueue.length > 0) {
          for (var i in window.xhrQueue) {
            ping(window.xhrQueue[i])
            window.xhrQueue.splice(i, 1)
            clearInterval(window.pingInterval)
          }
        }
        // Otherwise, just make the singular request
        else {
          mainRequest()
        }
        // Reset xhrQueue since stuff is successful, change connection to true, and unset onbeforeunload message
        window.xhrQueue = []
        window.connectionState = true
      }
      // If there was a problem with the request
      else {
        // Notify the user their internet is down
        if (window.connectionState === true) {
          setTimeout(function() { alert("It seems you have momentarily lost internet connectivity.") }, 1)
        }
        // If there are no requests in the xhrQueue, create the timeout. Otherwise, just add to the queue
        if (window.xhrQueue.length === 0) {
          window.pingInterval = setInterval(function(){ ping() }, 3000)
        }
        // Add the request to the xhrQueue to be processed in order
        if (typeof(mainRequest) === "function") {
          window.xhrQueue.push(mainRequest)
        }
        window.connectionState = false
      }
    }
  }
  pingXhr.open("GET","/some/url/here",true)
  pingXhr.send()
}

2 个答案:

答案 0 :(得分:1)

这将是因为你一次性解雇所有人,有些人会比其他人更长时间回来,所以他们的处理程序将首先运行。

我建议您使用回调一次发送一个来发送下一个

答案 1 :(得分:1)

看起来你正在使用push()在队列中放置条目,然后在循环中使用splice()来删除它们。这不太可能正常工作 - 它会跳过其中的一些/大部分,因为当你迭代它们时,splice会修改数组中的索引。

如果你将循环更改为总是取消第一个元素,它将更好地工作。

编辑添加:你可能也不想在这里做一个for-in循环。在迭代时修改对象的键通常不是一个好主意。

类似的东西:

while (window.xhrQueue.length > 0) {
    ping(window.xhrQueue[0]);
    window.xhrQueue.splice(0, 1);
}

或者不是试图同时运行所有排队的请求,而是让onreadystatechange处理程序从队列中获取下一个条目并发送该请求。

相关问题