转载自:http://www.runoob.com/js/js-cookies.html
使用JS的基本功能实现以下功能。
我们将创建 cookie 来存储访问者名称。
首先,访问者访问 web 页面, 他将被要求填写自己的名字。该名字会存储在 cookie 中。
访问者下一次访问页面时,他会看到一个欢迎的消息。
在这个实例中我们会创建 3 个 JavaScript 函数:
设置 cookie 值的函数
获取 cookie 值的函数
检测 cookie 值的函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>cookie验证</title>
</head>
<head>
<script>
function setCookie(cname,cvalue,exdays){
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie(){
var user=getCookie("username");
if (user!=""){
alert("Welcome again " + user);
}
else {
user = prompt("Please enter your name:","");
if (user!="" && user!=null){
setCookie("username",user,30);
}
}
}
</script>
</head>
<pre>
我们将创建 cookie 来存储访问者名称。
首先,访问者访问 web 页面, 他将被要求填写自己的名字。该名字会存储在 cookie 中。
访问者下一次访问页面时,他会看到一个欢迎的消息。
在这个实例中我们会创建 3 个 JavaScript 函数:
设置 cookie 值的函数
获取 cookie 值的函数
检测 cookie 值的函数
具体网页:http://www.runoob.com/js/js-cookies.html
</pre>
<body οnlοad="checkCookie()"></body>
</html>