【问题标题】:jQuery ajax cache with deferred (when duplicate requests are fired simultaneously)带有延迟的 jQuery ajax 缓存(当同时触发重复请求时)
【发布时间】:2011-05-04 22:17:32
【问题描述】:

我想实现一个健壮的 ajax 缓存并寻找合适的模式 - 可能使用新的 jquery 1.5.2 延迟对象。

这里的最佳答案:

How can jQuery deferred be used?

接近了,但失败的地方是如果两个 ajax 请求同时触发,仍然会有 2 个请求到服务器。由于尚未收到响应,因此尚未填充缓存。

我想要一个只向服务器发出 1 个请求但会向两者都返回响应的实现。

【问题讨论】:

    标签: jquery ajax jquery-deferred


    【解决方案1】:

    在我看来,这是完全未经测试的:

    (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,因此可以透明地处理并发。

    【讨论】:

      猜你喜欢
      • 2017-01-23
      • 1970-01-01
      • 2011-02-26
      • 2016-09-11
      • 2011-03-31
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      相关资源
      最近更新 更多