我想实现一个强大的 ajax 缓存并寻找合适的模式 - 可能使用新的 jquery 1.5.2 延迟对象。
这里的最佳答案:
How can jQuery deferred be used?
已经很接近了,但它的缺点是如果同时触发两个 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,因此并发处理是透明的。
关于具有延迟功能的 jQuery ajax 缓存(当同时触发重复请求时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5890512/