我有一段 JS 向我的服务器发出 AJAX 请求,它返回一些 JSON。它看起来像这样:
$.ajax({
dataType: 'json',
type: 'GET',
localCache: true,
cacheTTL: 6,
url: url
}).fail(function(jqXHR, textStatus, something) {
//Display error message
}).done(function(data) {
//Do stuff with the data
});
现在我想做的是使用localStorage在客户端缓存json,这样如果缓存足够新鲜,请求就不会真正发送,而是使用缓存。我一直在使用 Paul Irish 的 ajax-localstorage-cache 插件来执行此操作,但不幸的是它不支持延迟回调,因此我已尽力对其进行修改以使其支持。
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
// Cache it ?
if ( !Modernizr.localstorage || !options.localCache ) return;
var hourstl = options.cacheTTL || 5;
var cacheKey = options.cacheKey || options.url.replace( /jQuery.*/,'' ) + options.type + options.data;
// if there's a TTL that's expired, flush this item
var ttl = localStorage.getItem(cacheKey + 'cachettl');
if ( ttl && ttl < +new Date() ){
localStorage.removeItem( cacheKey );
localStorage.removeItem( cacheKey + 'cachettl' );
ttl = 'expired';
}
var value = localStorage.getItem( cacheKey );
if ( value ) {
//In the cache? So get it, apply done callback & abort the XHR request
// parse back to JSON if we can.
if ( options.dataType.indexOf( 'json' ) === 0 ) value = JSON.parse( value );
//Pass value back to the done callback somehow...
// Abort is broken on JQ 1.5 :(
jqXHR.abort();
} else {
$.Deferred(function(defer) {
//If it not in the cache, we change the done callback, just put data on localstorage and after that apply the initial callback
if ( jqXHR.done ) {
jqXHR.realdone = jqXHR.done;
}
jqXHR.done(function(data) {
var strdata = data;
if ( options.dataType.indexOf( 'json' ) === 0 ) strdata = JSON.stringify( data );
// Save the data to localStorage catching exceptions (possibly QUOTA_EXCEEDED_ERR)
try {
localStorage.setItem( cacheKey, strdata );
// store timestamp
if ( ! ttl || ttl === 'expired' ) {
localStorage.setItem( cacheKey + 'cachettl', +new Date() + 1000 * 60 * 60 * hourstl );
}
} catch (e) {
// Remove any incomplete data that may have been saved before the exception was caught
localStorage.removeItem( cacheKey );
localStorage.removeItem( cacheKey + 'cachettl' );
if ( options.cacheError ) options.cacheError( e, cacheKey, strdata );
}
if ( jqXHR.realdone ) jqXHR.realdone( defer.resolve );
}).fail(defer.reject)
}).promise(jqXHR);
}
});
我遇到的问题是我似乎无法弄清楚如何将缓存值恢复为原始done
回调。如果我这样做jqXHR.abort()
,fail
回调将运行,如果我不中止,那么它只会正常执行请求。
我做错了什么吗?如果是这样,什么是更聪明的方法呢?如果没有,我怎样才能将缓存值返回到完成回调(或至少将其返回到失败回调)?