带有延迟的jQuery ajax缓存(当同时触发重复请求时)
我想实现一个健壮的ajax缓存并寻找合适的模式——可能使用新的jQuery1.5.2延迟对象 答案如下: 很接近,但失败的地方是,如果两个ajax请求同时触发,那么仍然会有两个对服务器的请求。由于响应尚未到来,缓存尚未填充带有延迟的jQuery ajax缓存(当同时触发重复请求时),jquery,ajax,jquery-deferred,Jquery,Ajax,Jquery Deferred,我想实现一个健壮的ajax缓存并寻找合适的模式——可能使用新的jQuery1.5.2延迟对象 答案如下: 很接近,但失败的地方是,如果两个ajax请求同时触发,那么仍然会有两个对服务器的请求。由于响应尚未到来,缓存尚未填充 我想要一个只向服务器发出1个请求的实现,但会将响应返回给这两个服务器。从我的想法来看,这里有一些完全未经测试的东西: (function( $ ) { // Perform a cached ajax request // keyFn is a functi
我想要一个只向服务器发出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,因此并发性的处理是透明的