注:参考 《JavaScript权威指南》第十六章 脚本化cookie
实现功能:将用户名存入到cookie中,关闭浏览器后,再次访问页面,可以取出cookie中值,进行相关验证性操作。(本例是对cookie的学习记录,仔细阅读,可了解关于cookie的基本应用。)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie的存储和读取</title>
</head>
<body>
<h3><b>Cookie的存储和读取</b></h3>
<form name="cookieForm">
<table border="1">
<tr>
<td>用户名:</td>
<td><input type="text" name="userName" size="25"></td>
</tr>
<tr>
<td>密码:</td><td><input type="password" name="password" size="27"></td>
</tr>
<tr>
<td>操作</td>
<td>
<input type="button" value="存储Cookie" οnclick="savaCookie()">
<input type="button" value="读取Cookie" οnclick="readCookie()">
</td>
</tr>
</table>
</form>
</body>
<script type="text/javascript"><!--
function savaCookie(){
var userName = document.cookieForm.userName.value;
//userName 用户名
var password = document.cookieForm.password.value;
//password 密码
var nextyear = new Date();
nextyear.setFullYear(nextyear.getFullYear()+1);
//nextyear 打印格式为 2011
var lastModified = document.lastModified;
//version 更改版本 lastModified打印格式为 05/27/2011 17:00:24
var cookieString= "userName="+ escape(userName)
+ ";password=" + escape(password) + ";version="
+ escape(lastModified) + ";expires=" + nextyear.toGMTString();
document.cookie =cookieString;
alert(cookieString);
}
function readCookie(){
var allcookies=document.cookie;
//读cookie属性。返回文档所有的cookie。
var posOfName = allcookies.indexOf("userName=");
//查找名为"userName"的开始位置。
if(posOfName!=-1){
var startOfName = posOfName+"userName=".length;
//cookie的值的开始
var endOfName = allcookies.indexOf(";",startOfName);
//cookie的值的结尾
if(endOfName == -1) endOfName = allcookies.length;
var nameValue = allcookies.substring(startOfName,endOfName);
nameValue = unescape(nameValue);
if(nameValue != "wuyechun"){
alert("非法用户");
}else{
alert("合法用户");
}
}
}
</script>
</html>
效果图:
说明:
1、输入用户名"wuyechun",点击"存储cookie",点击"读取cookie"。弹出对话框“合法用户”;
2、关闭浏览器,重新打开,点击"读取cookie"。弹出对话框“合法用户”;
3、点击"存储cookie",是将用户名"wuyechun"存入了cookie中,即使关掉了浏览器,再次打开,通过“读取cookie”读取了用户名,进行了判断。
看看本机中的cookie文件: