您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 常德分类信息网,免费分类信息发布

JavaScript如何实现前端缓存

2024/3/1 9:00:05发布22次查看
在前端浏览器中,有些数据(比如数据字典中的数据),可以在第一次请求的时候全部拿过来保存在js对象中,以后需要的时候就不用每次都去请求服务器了。对于那些大量使用数据字典来填充下拉框的页面,这种方法可以极大地减少对服务器的访问。这种方法特别适用于使用iframe的框架。
具体实现思路和方法:
创建一个cache.js文件:
1、前端页面,定义那些数据需要一次性拿到前端缓存,定义一个对象来保存这些数据:
/** * 定义需要在用户登录的时候获取到本地的数据字典类别 */ var clscodes = {"clscodes" : ["bool", "status", "user_type", "report_status" ] }; /** * 获取数据字典到本地 */ var dicts;
2、前端页面,定义一个函数来调用后台接口获取数据,然后保存到本地缓存对象(dicts)中。
function getdicts() { $.post(getcontextpath() + "/api/sys/getdictlist", clscodes, function(resultbean, status, xhrequest) { if (resultbean.data != undefined) { dicts = resultbean.data; } }, 'json'); }
在主页面加载的时候调用这个方法一次性获取数据并缓存起来。这样,以后需要同样的数据,就直接从本地对象dicts中获取了。
后端controller:
3、定义一个接口,根据前端的请求,查询数据库(或查询服务器缓存,如下面例子中)获取数据返回给前端:
/** * 根据多个分类编号获取多个字典集合 * @param clscodes * @return {{"clscode" : {"code1":"name1,"code2":"name2"...}}, ...} */ @suppresswarnings({ "unchecked", "rawtypes" }) @responsebody @requestmapping("getdictlist") public resultbean getdictlist(@requestparam(value = "clscodes[]", required = true) string[] clscodes) { resultbean rb = new resultbean(); map<string, map<string, string>> dictcache = (map<string, map<string, string>>) cachemanager.getinstance().get(cacheconstants.dict); map dictmap = new linkedhashmap<>(); //使用linkedhashmap保证顺序 if(dictcache != null){ for(string clscode: clscodes){ dictmap.put(clscode, dictcache.get(clscode)); } }else{ rb.setmessage("缓存中拿不到字典信息!"); rb.setsuccess(false); } rb.setdata(dictmap); return rb; }
相关推荐:
前端缓存机制的总结
写给前端的http缓存详解
前端几种本地缓存机制
使用js实现前端缓存
以上就是javascript如何实现前端缓存的详细内容。
常德分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录