我用js设置cookie的时候expires总是设置不成功
window.onload = function(){ var exp = new Date(); exp.setTime(exp.getTime() + 30 * 24 * 60 * 60 * 1000); exp = exp.toGMTString(); function setCookie(key, value, expires){ var cookieStr = key + "=" + value; if(expires){ cookieStr += "; " + "max-age" + "=" + 1000; } // cookieStr += "; domain=baidu.com; path=/"; document.cookie = cookieStr; console.log(document.cookie); } function getCookie(key){ var cookieName = key + "="; var startIndex = document.cookie.indexOf(cookieName); var value = null; if(startIndex != -1){ var endIndex = document.cookie.indexOf(";", startIndex); if(endIndex == -1){ endIndex = document.cookie.length; } value = document.cookie.substring(startIndex + cookieName.length, endIndex); } return value; } if(!getCookie("name")){ document.getElementById("result").innerHTML = "Welcome!"; setCookie("name", "xiaota", exp); } else{ document.getElementById("result").innerHTML = "Welcome " + getCookie("name") + "!"; }
调用setCookie函数的时候,传入时间,console.log打印的结果并没有expires,不知道怎么回事。
其实过期时间已经设好了,但是
max-age
和expires
是不可见的。document.cookie
里只能看到cookie的key:value
。目前大多数浏览器都可以查看cookie的
max-age
和expires
。以Chrome为例:在devTool - Application - Storage - Cookies里面可以看到cookie的所有属性。
function setCookie(name,value,days){//设置cookie
}