cookie 用来识别用户
1.创建一个欢迎的cookie
<html>
<head>
<script type="text/javascript">
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
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
}
function checkCookie()
{
username=getCookie('username')
if (username!=null && username!="")
{alert('Welcome again '+username+'!')}
else
{
username=prompt('Please enter your name:',"")
if (username!=null && username!="")
{
setCookie('username',username,365)
}
}
}
</script>
</head>
<body onLoad="checkCookie()">
</body>
</html>
完美的案例
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript">
var userName;
function button_click()
{
userName=readCookie("username");
if(userName){
alert("Hello "+userName+",I miss you")
}
else{
var userName=prompt("What is your name","Enter you name here")
writeCookie("username",userName,5);
}
}
</script>
<script>
//向cookie写入数据
function writeCookie(name, value, days) {
// 定义有效日期(cookie的有效时间)
var expires = "";
// 为有效日期赋值
if (days) {
var date = new Date();
//设置有效期(当前时间+时间段)
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));//时间段为毫秒数
expires = "; expires=" + date.toGMTString();
}
// 给cookie赋值 name, value和expiration date(有效期)
document.cookie = name + "=" + value + expires + "; path=/";
}
//读取cookie数据
function readCookie(name) {
var searchName = name + "=";
var cookies = document.cookie.split(';');
for(var i=0; i < cookies.length; i++) {
var c = cookies[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(searchName) == 0)
return c.substring(searchName.length, c.length);
}
return null;
}
//清楚所有的cookie
function eraseCookie(name) {
// 将时间设置成-1将清除存储在cookie中的数据
writeCookie(name, "", -1);
}
</script>
</head>
<input type="button" value="Click me" οnclick="button_click();" />
</body>
</html>