JS cookie 相关操作
1.设置cookie
function setCookie(name, value, liveMinutes) {
if (liveMinutes == undefined || liveMinutes == null) {
liveMinutes = 60 * 2;
}
if (typeof (liveMinutes) != 'number') {
liveMinutes = 60 * 2;//默认120分钟
}
var minutes = liveMinutes * 60 * 1000;
var exp = new Date();
exp.setTime(exp.getTime() + minutes + 8 * 3600 * 1000);
//path=/表示全站有效,而不是当前页
document.cookie = name + "=" + value + ";path=/;expires=" + exp.toGMTString();
}
2.读取cookie
function getCookie(name){
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return null;
}
3.校验cookie
function checkCookie(){
username=getCookie('username');
if (username!=null && username!=""){
alert('Welcome again '+username+'!');
}else {
username=prompt('Please enter your name:',"") ;
if (username!=null && username!=""){
setCookie('username',username,365);
}
}
}
总结:cookie介绍到此告一段落,希望对大家有所帮助!
我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=1npsq8ar4iw29
关注
关注下方微信公众号,可以及时获取到各种技术的干货哦,如果你有想推荐的帖子,也可以联系我。