jquery - 在 Event : navigator. onLine 之后重新启动基于 jquery xhr 对象的 Ajax 请求

标签 jquery ajax navigator

我们正在绑定(bind)全局 ajax 处理程序来检查浏览器是否离线:

$(document).ajaxSend(function(event, xhr, settings, response){  
   if(!navigator.onLine){  
        xhr.abort();  
   }  
}

然后我们向用户显示一个对话框,表明浏览器已离线,并绑定(bind)“在线”事件,以便在浏览器再次上线时隐藏该对话框。

是否有无论如何(即使是一个 hacky 的)来根据旧的适合旧上下文的旧 Ajax 请求重新启动 Ajax 请求?

最佳答案

这是我能想到的最干净的方法:

  1. 用于缓存 AJAX 请求设置的队列,以便每次后续调用都不会覆盖前一个调用
  2. 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/

相关文章:

javascript - Slick carousel centerMode 的问题 - 不断增长的中心元素

javascript - PHP 从 Ajax 调用接收空的 $_POST 变量

javascript - jQuery.fadeIn()/fadeOut()。无法在 IE7+8 下运行

javascript - 如何在 PHP 中点击按钮将数据插入数据库时​​增加进度条

javascript - 在 navigator.geolocation.getCurrentPosition 之外保存变量? (javascript)

带参数的 Flutter 初始路由

javascript - 在 mozilla Firefox 浏览器中切换多个摄像头

javascript - 使用 Jquery 从 Json 对象获取父节点

php - 如何在不重新加载页面的情况下更改 php 包含?

javascript - 表单数据通过ajax连同文本字段上传多个文件