Skip to content

Instantly share code, notes, and snippets.

@langemike
Created November 23, 2021 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save langemike/4a18911469badba1b532d22a41294219 to your computer and use it in GitHub Desktop.
Save langemike/4a18911469badba1b532d22a41294219 to your computer and use it in GitHub Desktop.
sessionstorage ajax request using jquery
var getCache = function(cacheKey, expireMinutes) {
var value = sessionStorage.getItem(cacheKey);
var timestamp = Math.floor(Date.now() / 1000);
var expireTime = timestamp - (expireMinutes * 60);
var data = null;
if (value === null) {
return null;
}
data = JSON.parse(value);
if (typeof data !== 'object') {
return null;
}
if (data.created < expireTime) {
sessionStorage.removeItem(cacheKey);
return null;
}
return data;
};
var setCache = function(cacheKey, value) {
var timestamp = Math.floor(Date.now() / 1000);
var data = {
value: value,
created: timestamp
};
sessionStorage.setItem(cacheKey, JSON.stringify(data));
}
var getData = function(url, cache) {
var cacheKey = 'cache_' + url;
var data = getCache(cacheKey, 15);
if (cache && data !== null) {
var d = $.Deferred();
d.resolve(data.value);
return d.promise();
}
return $.get(url).done(function(response) {
if (cache) {
setCache(cacheKey, response)
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment