Skip to content

Instantly share code, notes, and snippets.

@SaneMethod
Last active December 18, 2015 23:29
Show Gist options
  • Save SaneMethod/5861729 to your computer and use it in GitHub Desktop.
Save SaneMethod/5861729 to your computer and use it in GitHub Desktop.
Ajax transport example for json, for ajax caching.
/**
* This function performs the fetch from cache portion of the functionality needed to cache ajax
* calls and still fulfill the jqXHR Deferred Promise interface.
* See also $.ajaxPrefilter
* @method $.ajaxTransport
* @params options {Object} Options for the ajax call, modified with ajax standard settings
*/
$.ajaxTransport("json", function(options){
if (options.localCache)
{
var cacheKey = options.cacheKey ||
options.url.replace(/jQuery.*/, '') + options.type + options.data;
var value = storage.getItem(cacheKey);
if (value){
// In the cache? Get it, parse it to json, call the completeCallback with the fetched value.
if (options.dataType.indexOf( 'json' ) === 0) value = JSON.parse(value);
return {
send: function(headers, completeCallback) {
completeCallback(200, 'success', {json:value})
},
abort: function() {
console.log("Aborted ajax transport for json cache.");
}
};
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment