我有一个 AJAX 密集型应用程序,需要快速或同时发送多个 AJAX 请求。以下代码只是一个简单的包装器,用于发送我在整个应用程序中使用的 AJAX POST 调用。有 2 个警告:
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()
}