h5-localStorage实现缓存ajax请求数据

使用背景:要实现每次鼠标hover“能力雷达”,则显示能力雷达图(通过ajax请求数据实现雷达图数据显示),所以每次hover都去请求ajax会影响性能,因此这里要用到本地缓存。

实现:

此处是通过传id去请求能力雷达图数据,因此要setItem()的不止1个,所以当ajax返回result后,根据id去创建名称 

 $.ajax({
                type: "POST",
                cache: false,
                url: "/Question/GetShopRadarMap",
                data: {
                    shopId: id
                },
                contentType: "application/x-www-form-urlencoded",
                dataType: "json",
                async: false,
                success: function (result) {
                    localStorage.setItem("radarResult_" + id + "", JSON.stringify(result.resultList)); //存储的时候 使用JSON.stringify()将对象解析出字符串

            var resultList = result.resultList;
            // 执行能力雷达图的数据绑定及展示
} });

当鼠标再次hover能力雷达图的时候:根据id获取已经存储了的数据,就不用每次都去发送请求  

var storage = localStorage.getItem("radarResult_" + id + "");
 if (storage != null) {
            var resultList = JSON.parse(storage); // 从一个字符串中解析出json对象
            // 执行能力雷达图的数据绑定及展示
  } 
原文地址:https://www.cnblogs.com/ss977/p/7792385.html