1.项目中遇到的,两个页面频繁跳转,每次都请求一次接口,导致页面渲染更新缓慢,这时用到本地存储来避免频繁请求,前提是接口里的数据不是频繁更新的(以下是案例)
var getboxInfo = JSON.parse(localStorage.getItem("setboxInfo")) //这里获取存储的数据(将字符串转化为对象)
if(getboxInfo == null) { //判断如果当获取到的数据为null时请求接口
//获取接口信息
$.ajax({
url: “这里是接口地址”,
type: "get",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": TOKEN,
},
success: function(res) {
localStorage.setItem("setboxInfo",JSON.stringify(res)) //第一次请求成功把数据本地存储(对象转换为字符串)
$(".box_no").append(res.no); //编号
$(".qrcode_url").attr("src", res.qrcode_url); //图片
},
error: function(err) {
console.log(err)
}
})
} else { //否则直接拿本地数据渲染
$(".box_no").append(getboxInfo.no); //编号
$(".qrcode_url").attr("src",getboxInfo.qrcode_url); //图片
}