我想实现一个健壮的 ajax 缓存并寻找合适的模式——可能使用新的 jquery 1.5.2 延迟对象。
这里的最佳答案:
接近了,但失败的地方是如果同时触发两个 ajax 请求,仍然会有 2 个请求到服务器。由于尚未收到响应,因此尚未填充缓存。
我想要一个只向服务器发出 1 个请求的实现,但会将响应返回给两者。
我想实现一个健壮的 ajax 缓存并寻找合适的模式——可能使用新的 jquery 1.5.2 延迟对象。
这里的最佳答案:
接近了,但失败的地方是如果同时触发两个 ajax 请求,仍然会有 2 个请求到服务器。由于尚未收到响应,因此尚未填充缓存。
我想要一个只向服务器发出 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,因此并发处理是透明的。