---
title: "cookie示例：登陆页面中的记住密码功能"
author: "duyunfengsolo"
date: "2009-08-21T15:08:16Z"
tags: ["Go", "HTML", "JavaScript", "XHTML", "浏览器"]
slug: "cookie"
draft: false
lastmod: "2009-08-21T15:08:16Z"
id: 454476
url: "https://solodu.iteye.com/blog/454476"
---

CONTENT  
    login.html  
    welcome.html  
    cookie.js  
    common.js

 

login.html

Html代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/306195 "复制代码")

01. &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"**&gt;**
02. **&lt;html** xmlns="http://www.w3.org/1999/xhtml"**&gt;**
03. **&lt;head&gt;**
04. **&lt;meta** http-equiv="Content-Type" content="text/html; charset=gb2312" **/&gt;**
05. **&lt;title&gt;**login**&lt;/title&gt;**
06. **&lt;script** type="text/javascript" src="cookie.js"**&gt;&lt;/script&gt;**
07. **&lt;script** type="text/javascript" src="common.js"**&gt;&lt;/script&gt;**
08. **&lt;/head&gt;**
09. **&lt;body&gt;**
10. **&lt;form** action=""**&gt;**
11. **&lt;p&gt;**
12. **&lt;span&gt;**UserName:**&lt;/span&gt;**
13. **&lt;input** id="userName" type="text" value=""**/&gt;&lt;/p&gt;**
14. **&lt;p&gt;**
15. **&lt;span&gt;**Password:**&lt;/span&gt;**
16. **&lt;input** id="password" type="password" value=""**/&gt;&lt;/p&gt;**
17. **&lt;p&gt;**
18. **&lt;span** style="font-size:12px; color:blue;"**&gt;**记住密码**&lt;/span&gt;**
19. **&lt;input** id="saveCookie" type="checkbox" value="" **/&gt;&lt;/p&gt;**
20. **&lt;p&gt;**
21. **&lt;input** id="submit" type="button" value="GO" **/&gt;**
22. **&lt;/p&gt;**
23. **&lt;/form&gt;**
24. **&lt;/body&gt;**
25. **&lt;/html&gt;**

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>login</title>
<script type="text/javascript" src="cookie.js"></script>
<script type="text/javascript" src="common.js"></script>
</head>
<body>
<form action="">
<p>
    <span>UserName:</span>
    <input id="userName" type="text" value=""/></p>
<p>
    <span>Password:</span>
    <input id="password" type="password" value=""/></p>
<p>
    <span style="font-size:12px; color:blue;">记住密码</span>
    <input id="saveCookie" type="checkbox" value="" /></p>
<p>
    <input id="submit" type="button" value="GO" />
</p>
</form>
</body>
</html>
```

 

welcome.html

Html代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/306195 "复制代码")

01. &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"**&gt;**
02. **&lt;html** xmlns="http://www.w3.org/1999/xhtml"**&gt;**
03. **&lt;head&gt;**
04. **&lt;meta** http-equiv="Content-Type" content="text/html; charset=gb2312" **/&gt;**
05. **&lt;title&gt;**welcome**&lt;/title&gt;**
06. **&lt;/head&gt;**
07. **&lt;body&gt;**
08. **&lt;h1&gt;**Welcome!**&lt;/h1&gt;**
09. **&lt;a** href="login.html"**&gt;**点击返回登陆框**&lt;/a&gt;**
10. **&lt;/body&gt;**
11. **&lt;/html&gt;**

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>welcome</title>
</head>
<body>
<h1>Welcome!</h1>
<a href="login.html">点击返回登陆框</a>
</body>
</html>
```

 

cookie.js

Js代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/306195 "复制代码")

01. //新建cookie。
02. //hours为空字符串时,cookie的生存期至浏览器会话结束。hours为数字0时,建立的是一个失效的cookie,这个cookie会覆盖已经建立过的同名、同path的cookie（如果这个cookie存在）。
03. **function** setCookie(name,value,hours,path){
04. **var** name = escape(name);
05. **var** value = escape(value);
06. **var** expires = **new** Date();
07. expires.setTime(expires.getTime() + hours\*3600000);
08. path = path == "" ? "" : ";path=" + path;
09. \_expires = (**typeof** hours) == "string" ? "" : ";expires=" + expires.toUTCString();
10. document.cookie = name + "=" + value + \_expires + path;
11. }
12. //获取cookie值
13. **function** getCookieValue(name){
14. **var** name = escape(name);
15. //读cookie属性，这将返回文档的所有cookie
16. **var** allcookies = document.cookie;
17. //查找名为name的cookie的开始位置
18. name += "=";
19. **var** pos = allcookies.indexOf(name);
20. //如果找到了具有该名字的cookie，那么提取并使用它的值
21. **if** (pos != -1){                                             //如果pos值为-1则说明搜索"version="失败
22. **var** start = pos + name.length;                  //cookie值开始的位置
23. **var** end = allcookies.indexOf(";",start);        //从cookie值开始的位置起搜索第一个";"的位置,即cookie值结尾的位置
24. **if** (end == -1) end = allcookies.length;        //如果end值为-1说明cookie列表里只有一个cookie
25. **var** value = allcookies.substring(start,end);  //提取cookie的值
26. **return** unescape(value);                           //对它解码
27. }
28. **else** **return** "";                                             //搜索失败，返回空字符串
29. }
30. //删除cookie
31. **function** deleteCookie(name,path){
32. **var** name = escape(name);
33. **var** expires = **new** Date(0);
34. path = path == "" ? "" : ";path=" + path;
35. document.cookie = name + "="+ ";expires=" + expires.toUTCString() + path;
36. }

```
//新建cookie。
//hours为空字符串时,cookie的生存期至浏览器会话结束。hours为数字0时,建立的是一个失效的cookie,这个cookie会覆盖已经建立过的同名、同path的cookie（如果这个cookie存在）。
function setCookie(name,value,hours,path){
    var name = escape(name);
    var value = escape(value);
    var expires = new Date();
    expires.setTime(expires.getTime() + hours*3600000);
    path = path == "" ? "" : ";path=" + path;
    _expires = (typeof hours) == "string" ? "" : ";expires=" + expires.toUTCString();
    document.cookie = name + "=" + value + _expires + path;
}
//获取cookie值
function getCookieValue(name){
    var name = escape(name);
    //读cookie属性，这将返回文档的所有cookie
    var allcookies = document.cookie;       
    //查找名为name的cookie的开始位置
    name += "=";
    var pos = allcookies.indexOf(name);    
    //如果找到了具有该名字的cookie，那么提取并使用它的值
    if (pos != -1){                                             //如果pos值为-1则说明搜索"version="失败
        var start = pos + name.length;                  //cookie值开始的位置
        var end = allcookies.indexOf(";",start);        //从cookie值开始的位置起搜索第一个";"的位置,即cookie值结尾的位置
        if (end == -1) end = allcookies.length;        //如果end值为-1说明cookie列表里只有一个cookie
        var value = allcookies.substring(start,end);  //提取cookie的值
        return unescape(value);                           //对它解码      
        }   
    else return "";                                             //搜索失败，返回空字符串
}
//删除cookie
function deleteCookie(name,path){
    var name = escape(name);
    var expires = new Date(0);
    path = path == "" ? "" : ";path=" + path;
    document.cookie = name + "="+ ";expires=" + expires.toUTCString() + path;
}
```

 

common.js

Js代码 [![复制代码](http://sunxboy.iteye.com/images/icon_copy.gif)](http://sunxboy.iteye.com/blog/306195 "复制代码")

01. **function** $(objStr){**return** document.getElementById(objStr);}
02. window.onload = **function**(){
03. //分析cookie值，显示上次的登陆信息
04. **var** userNameValue = getCookieValue("userName");
05. $("userName").value = userNameValue;
06. **var** passwordValue = getCookieValue("password");
07. $("password").value = passwordValue;
08. //写入点击事件
09. $("submit").onclick = **function**()
10. {
11. **var** userNameValue = $("userName").value;
12. **var** passwordValue = $("password").value;
13. //服务器验证（模拟）
14. **var** isAdmin = userNameValue == "admin" && passwordValue =="123456";
15. **var** isUserA = userNameValue == "userA" && passwordValue =="userA";
16. **var** isMatched = isAdmin || isUserA;
17. **if**(isMatched){
18. **if**( $("saveCookie").checked){
19. setCookie("userName",$("userName").value,24,"/");
20. setCookie("password",$("password").value,24,"/");
21. }
22. alert("登陆成功,欢迎你," + userNameValue + "!");
23. self.location.replace("welcome.html");
24. }
25. **else** alert("用户名或密码错误，请重新输入！");
26. }
27. }

```
function $(objStr){return document.getElementById(objStr);}
window.onload = function(){
    //分析cookie值，显示上次的登陆信息
    var userNameValue = getCookieValue("userName");
    $("userName").value = userNameValue;
    var passwordValue = getCookieValue("password");
    $("password").value = passwordValue;    
    //写入点击事件
    $("submit").onclick = function()
    {
        var userNameValue = $("userName").value;
        var passwordValue = $("password").value;
        //服务器验证（模拟）    
        var isAdmin = userNameValue == "admin" && passwordValue =="123456";
        var isUserA = userNameValue == "userA" && passwordValue =="userA";
        var isMatched = isAdmin || isUserA;
        if(isMatched){
            if( $("saveCookie").checked){  
                setCookie("userName",$("userName").value,24,"/");
                setCookie("password",$("password").value,24,"/");
            }    
            alert("登陆成功,欢迎你," + userNameValue + "!");
            self.location.replace("welcome.html");
        }
        else alert("用户名或密码错误，请重新输入！");    
    }
}
```