我有一块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
回调,如果我不中止,那么它只会正常执行请求。
我做错了什么吗?如果是这样,那么更聪明的方法是什么?如果没有,我怎样才能将缓存的值恢复为完成回调(或者至少将其转换为失败回调)?
答案 0 :(得分:0)
您可以考虑为ajax调用设置包装器。如下所示:
$.myAjax = function(params,doneCb,failCb){ //doneCb: doneCallback
var data = getFromLocalStorage(params),
if( data) {
var dfd = $.Deferred();
dfd.done(doneCb);
}else{
dfd = $.ajax(params).done(function(resp){
// add to localStorage
doneCb && doneCb(resp);
}).fail(failCb)
return dfd;
}
答案 1 :(得分:0)