我们正在绑定(bind)全局 ajax 处理程序来检查浏览器是否离线:
$(document).ajaxSend(function(event, xhr, settings, response){
if(!navigator.onLine){
xhr.abort();
}
}
然后我们向用户显示一个对话框,表明浏览器已离线,并绑定(bind)“在线”事件,以便在浏览器再次上线时隐藏该对话框。
是否有无论如何(即使是一个 hacky 的)来根据旧的适合旧上下文的旧 Ajax 请求重新启动 Ajax 请求?
最佳答案
这是我能想到的最干净的方法:
- 用于缓存 AJAX 请求设置的队列,以便每次后续调用都不会覆盖前一个调用
ajaxSend()
处理程序中的条件,用于将调用推送到队列上以供稍后使用或执行整个队列。!(function($, window, undefined){ var ajaxRequestQueue = [], // queue for requests that were made while offline isProcessingQueue = false; function processRequestQueue() { if (isProcessingQueue === true) { return; } isProcessingQueue = true; while (settings = ajaxRequestQueue.shift()) { $.ajax(settings); } isProcessingQueue = false; } $(document).ajaxSend(function(event, xhr, settings, response){ if (!navigator.onLine) { // abort the original request xhr.abort(); // push a copy of the request's settings on the queue ajaxRequestQueue.push($.extend(true, {}, settings)); } else if (ajaxRequestQueue.length > 0 && isProcessingQueue === false) // there are calls on queue and we haven't triggered 'ajaxSend' ourselves { processRequestQueue(); } }); // Bind to start processing the queue when the browser comes back online window.addEventListener("online", processRequestQueue); })(jQuery, window)
关于jquery - 在 Event : navigator. onLine 之后重新启动基于 jquery xhr 对象的 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8849457/