完整的cookie形式:
document.cookie = “user=xxx;expires=失效时间;path=访问路径;domain=访问域名;secure=安全https通信”
//保存cookie,并显示.
document.cookie = "user=" + encodeURIComponent("粒");
alert(decodeURIComponent(document.cookie));
保存cookie时候有个会话过期时间.如果没有设置,会在浏览器关闭的时候自动清理cookie.
//设置过期时间,过期cookie自动删除
var date = new Date();
date.setDate(date.getDate()+7);
document.cookie = "user=" + encodeURIComponent("粒")+";expires="+date;
alert(decodeURIComponent(document.cookie));
//删除cookie
document.cookie = "user=" + encodeURIComponent("粒")+";expires="+new Date(0);
//设置cookie
function setCookie(name, value, expires, path, domain, secure) {
var cookieName = encodeURIComponent(name) + '=' + encodeURIComponent(value);
if (expires instanceof Date) {
cookieName += '; expires=' + expires;
}
if (path) {
cookieName += '; path=' + path;
}
if (domain) {
cookieName += '; domain=' + domain;
}
if (secure) {
cookieName += '; secure';
}
document.cookie = cookieName;
}
//获取Cookie
function getCookie(name) {
var cookieName = encodeURIComponent(name) + '=';
var cookieStart = document.cookie.indexOf(cookieName);
var cookieValue = null;
if (cookieStart > -1) {
var cookieEnd = document.cookie.indexOf(';', cookieStart);
if (cookieEnd == -1) {
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
}
return cookieValue;
}
alert(getCookie('email'));
//过期时间
function setCookieDate(day) { //传递一个天数,比如传递7,就7天后失效
var date = null;
if (typeof day == 'number' && day > 0) {
date = new Date();
date.setDate(date.getDate() + day);
} else {
throw new Error('您传递的天数不合法!必须是数字且大于0');
}
return date;
}