diff --git a/README.md b/README.md index 33a144e..1b3967e 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,8 @@ $.ajax({ cacheTTL: 1, // Optional. In hours. Can be used with float to indicate part of an hour, e.g. 0.5. cacheKey: 'post', // optional. - isCacheValid: function () { // optional. - return true; + isCacheValid: function (data) { // optional. + return data && data.code === '0'; }, isResponseValid: function (data, status, jqXHR) { // optional. return data.code === '0'; diff --git a/jquery-ajax-localstorage-cache.js b/jquery-ajax-localstorage-cache.js index 85d2350..88c5c86 100644 --- a/jquery-ajax-localstorage-cache.js +++ b/jquery-ajax-localstorage-cache.js @@ -83,13 +83,22 @@ responseValid = options.isResponseValid, thenResponse = options.thenResponse || null, ttl, + dataType, value; if (!storage) return; ttl = storage.getItem(cacheKey + 'cachettl'); - if (cacheValid && typeof cacheValid === 'function' && !cacheValid()){ + value = storage.getItem(cacheKey); + + if (value){ + dataType = options.dataType || storage.getItem(cacheKey + 'dataType') || 'text'; + if (dataType.toLowerCase().indexOf('json') !== -1) value = JSON.parse(value); + } + + if (cacheValid && typeof cacheValid === 'function' && !cacheValid(value)){ removeFromStorage(storage, cacheKey); + value = null; ttl = 0; } @@ -98,7 +107,6 @@ ttl = 0; } - value = storage.getItem(cacheKey); if (!value){ // If value not in the cache, add a then block to request to store the results on success. jqXHR.then(thenResponse).then(function(data, status, jqXHR){