2

堅牢なajaxキャッシュを実装し、適切なパターンを探したいと思います。おそらく、新しいjquery1.5.2遅延オブジェクトを使用します。

ここでの一番の答え:

jQuery deferredはどのように使用できますか?

近づいていますが、失敗するのは、2つのajaxリクエストが同時に発生した場合でも、サーバーへのリクエストは2つあります。応答がまだ入っていないため、キャッシュにはまだデータが入力されていません。

サーバーに対して1つのリクエストのみを起動するが、両方にレスポンスを返す実装が必要です。

4

1 に答える 1

3

私の頭の上から、これは完全にテストされていないものです:

(function( $ ) {
    // Perform a cached ajax request
    // keyFn is a function that takes ajax options
    // and returns a suitable cache key
    jQuery.cachedAjax = function( keyFn ) {
        // Cache for jqXHR objects
        var cache = {};
        // Actual function to perform cached ajax calls
        return function( url, options ) {
            // If url is an object, simulate pre-1.5 signature
            if ( typeof url === "object" ) {
                options = url || {};
                url = undefined;
            // else, add the url into the options  
            } else if ( url ) {
                options = $.extend( {}, options || {} );
                options.url = url + "";
            }
            // Get the cache key
            var key = keyFn( options );
            // If not cached yet, cache it
            if ( !cache[ key ] ) {
                cache[ key ] = $.ajax( options );
            } else {
                // If already cached, ensure success, error
                // and complete callbacks are properly attached
                for( var cbType in { success: 1, error: 1, complete: 1 } ) {
                    cache[ key ][ cbType ]( options[ cbType ] );
                }
            }
            // Return the jqXHR for this key
            return cache[ key ];
        };
    };
})( jQuery ):

// Create a method that caches by url    
jQuery.ajaxCachedByURL = jQuery.cachedAjax(function( options ) {
    return options.url;
};

// Use the method just like ajax      
jQuery.cachedAjax( url, options ).then( successCallback, errorCallback );

アイデアは、値ではなく jqXHR をキャッシュに保存することです。リクエストが一度開始されるとすぐに、それがすでに終了しているか実行中であるかは問題ではありません。実際には、キャッシュされた ajax メソッドをさらに呼び出すと、同じ jqXHR が返されるため、並行性は透過的に処理されます。

于 2011-05-08T01:18:15.477 に答える