2

ブラウザーがオフラインになったかどうかを確認するために、グローバルな ajax ハンドラーをバインドしています。

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

次に、ブラウザがオフラインになったことを示すダイアログをユーザーに表示し、「オンライン」イベントにバインドして、ブラウザが再びオンラインになったときにダイアログを非表示にします。

古いコンテキストに適合する古いものに基づいてAjaxリクエストを再起動するとにかく(ハックなものでも)ありますか?

4

2 に答える 2

2

jQuery を使用してオブジェクトのクローンを作成し、ブラウザがオンラインに戻ったときに呼び出しを再開することができます。

// Deep copy
var savedXhr= jQuery.extend(true, {}, xhr);

これが本当に機能するかどうかわからないので、試してみてください

編集 - 試してみましたが、そのオブジェクトで send() を呼び出すことはできません。これはxhr、元のリクエストではなく、jQuery によって作成された「偽の」オブジェクトであるためです。別のアプローチとして、設定オブジェクトを保存してから、それらの設定で別の $.ajax 呼び出しを開始します。基本的にあなたはそうします

var settingsSaved;

$(document).ajaxSend(function(event, xhr, settings, response) {
    if (!navigator.onLine) {
        settingsSaved = jQuery.extend(true, {}, settings);
        xhr.abort();
    } else {
        //Send the request with the old settings
        $.ajax(settingsSaved);
        //abort the new request
        xhr.abort();
    }
}

$.ajax を呼び出すたびに別のイベントがトリガーされるため、正確なフロー制御が必要になることに十分注意してください。オブジェクトの値を使用ajaxSendして新しいイベントを開始することもできます。XMLHTTPRequestsettingsSaved

このフィドルを見てください。最初にボタンをクリックすると、通話が中止されます。コールが古い設定で 2 回目に開始され、それ以降はすべてのリクエストが正常です。

http://jsfiddle.net/hFmWX/

于 2012-01-13T11:02:14.110 に答える
2

これが私が考えることができる最もクリーンなアプローチです:

  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)
    
于 2012-01-26T14:12:21.140 に答える