1.基本方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| var MyLocalStorage = { Cache: {
put: function (key, stringVal, time) { try { if (!localStorage) { return false; } if (!time || isNaN(time)) { time = 1800; } var cacheExpireDate = (new Date() - 1) + time * 1000; var cacheVal = { val: stringVal, exp: cacheExpireDate }; localStorage.setItem(key, JSON.stringify(cacheVal)); } catch (e) { } }, get: function (key) { try { if (!localStorage) { return false; } var cacheVal = localStorage.getItem(key); var result = JSON.parse(cacheVal); var now = new Date() - 1; if (!result) { return null; } if (now > result.exp) { this.remove(key); return ""; } return result.val; } catch (e) { this.remove(key); return null; } }, remove: function (key) { if (!localStorage) { return false; } localStorage.removeItem(key); }, clear: function () { if (!localStorage) { return false; } localStorage.clear(); } } }
function getHotList() { try { var cache = MyLocalStorage.Cache.get("cacheKey"); if (cache == null) { } } catch (e) { } } getHotList();
|
原文链接:https://www.bbsmax.com/A/kjdwqOp2JN/
2.简单运用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| function dyajax{ var url = "ajax请求地址" $.ajax({ url: url, type: "post", data: {}, dataType: "json", success: function (resultAll) { MyLocalStorage.Cache.put(datalist, resultAll.data, 60 * 10); resultAll.data.list.sort(function (a, b) { return b.publishDate - a.publishDate }); var listlength = resultAll.data.totalCount; if (listlength != 0) {
$.each(resultAll.data.list, function (i, result) { }); } } }) }
function ajaxfun { console.log(MyLocalStorage.Cache.get('localStorage中指定存储键值')) if (window.localStorage.getItem('localStorage中指定存储键值')) { try { var cache = MyLocalStorage.Cache.get('localStorage中指定存储键值'); console.log(cache) if (cache == null) { console.log('有缓存,但过期,重新调取接口') dyajax() } } catch (e) { console.log('发生异常' + e) } var userinfo = cache.list; userinfo.sort(function (a, b) { return b.publishDate - a.publishDate }); var listlength = cache.totalCount; if (listlength != 0) { console.log('有缓存,未过期,正常拼接') $.each(userinfo, function (i, result) { }); } }
else { dyajax() } }
|