以下是告诉用户上次访问页面的脚本+ HTML。toDateString有什么问题
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cookie</title>
<script type="text/javascript">
window.onload = initLastVisit;
function initLastVisit() {
var now = new Date();
var last = new Date();
now.setMonth(now.getMonth()+6);
document.cookie = "lastVisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString();
document.getElementById("lastVisitedOn").innerHTML = document.cookie.split("=")[1];
}
</script>
</head>
<body>
<form>
<label>Enter your name <input type="text" id="name_field" /></label> <br/>
</form>
<h1 id="lastVisitedOn"></h1>
</body>
</html>
在上面的脚本中设置cookie的语句是:document.cookie = "lastVisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString();
。如果在此我用now.toDateString()
替换now.toGMTString()
在浏览器中的过期时间是“当我关闭浏览器时失效”。这是为什么 ? 可以用toGMTString
。预计截止日期为2012年3月。
为什么要使用“toDateString()”而不是“toGMTString()”?或者你只是好奇为什么事情是这样的? – Pointy
@ Pointy _curious_ –
.toDateStr趋向于以不同于.toGMTString的格式输出。最有可能的是,无论您的浏览器输出什么内容,都无法将其作为cookie使用的适当日期进行整合,因此只需将其解释为0即可。 –