获取和设置Cookie
Sonder
2020-04-28
718字
2分钟
浏览 (2.5k)
设置:
function setCookie(c_name, value, expiredays) {
var exdate = new Date();
exdate.setTime(Number(exdate) + expiredays);
document.cookie = c_name + "=" + escape(value) ;
}
获取:
function getCookie(c_name) {
if(document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");//获取字符串的起点
if(c_start != -1) {
c_start = c_start + c_name.length + 1;//获取值的起点
c_end = document.cookie.indexOf(";", c_start);//获取结尾处
if(c_end == -1) c_end = document.cookie.length;//如果是最后一个,结尾就是cookie字符串的结尾
return decodeURI(document.cookie.substring(c_start, c_end));//截取字符串返回
}
}
return "";
}
示例:
var userName = getCookie("user_name");
console.log(userName)