cookie与localStorage的应用
cookie
-
存储的数据是临时的
-
可以通过JS设置过期时间
-
只能存储文本字符串
示例
//读取Cookie
var listData=getCookie("videolist1");
//判断listData是否存在
if(listData!=""){
//将字符串转换成数组
var shuzu=listData.split(",");
//遍历数组
for (var index = 0; index < shuzu.length; index++) {
$("#ks-model .ks-li").html(shuzu[index]);
$("#ks-ol").append($("#ks-model").html());
}
}else{
//testVideoList不存在时执行
getUserInfo();
}
//请求用户数据
function getUserInfo(){
$.ajax({
url: "/plus/json.aspx",
type: "get",
dataType: "json",
beforeSend: function () {
$(".qingqiu").show();
},
success: function (res) {
$(".qingqiu").hide();
//创建数组
var ls=[];
for (var index = 0; index < res.data.length; index++) {
const element = res.data[index];
$("#ks-model .ks-li").attr("data-id", element.periodid);
$("#ks-model .ks-li").html(element.periodname);
$("#ks-model .ks-li").attr("href", "ksdetails.html?prdid=" + element.periodid);
$("#ks-ol").append($("#ks-model").html());
//添加数据到数组
ls.push(element.periodname);
}
//将数组转换成字符串
var vList=ls.concat();
//写入Cookie
setCookie('videolist1', vList, 1 );
},
error: function (e) {
$(".qingqiu").html("加载失败!");
}
})
}
// 写入缓存的方法 三个参数分别是 cookie名称 cookie值 cookie过期时间
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
// 读取缓存的方法
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
localStorage
-
存储的数据时永久存在本地的
示例
//读取localStorage
var testVideoList= localStorage.getItem("testVideo");
//判断是否存在
if(testVideoList!=null){
//遍历JSON对象
$.each(JSON.parse(testVideoList),function(idx,obj){
$("#ks-model .ks-li").attr("data-id", obj.periodid);
$("#ks-model .ks-li").html(obj.periodname);
$("#ks-model .ks-li").attr("href", "ksdetails.html?prdid=" + obj.periodid);
$("#ks-ol").append($("#ks-model").html());
})
}else{
//testVideoList不存在时执行
getUserInfo();
}
//请求用户数据
function getUserInfo(){
$.ajax({
url: "/plus/json.aspx",
type: "get",
dataType: "json",
beforeSend: function () {
$(".qingqiu").show();
},
success: function (res) {
//写入数据到localStorage ,存为JSON字符串
localStorage.setItem("testVideo",JSON.stringify(res.data));
$(".qingqiu").hide();
for (var index = 0; index < res.data.length; index++) {
const element = res.data[index];
$("#ks-model .ks-li").attr("data-id", element.periodid);
$("#ks-model .ks-li").html(element.periodname);
$("#ks-model .ks-li").attr("href", "ksdetails.html?prdid=" + element.periodid);
$("#ks-ol").append($("#ks-model").html());
}
},
error: function (e) {
$(".qingqiu").html("加载失败!");
}
})
}