1. 程式人生 > >瀏覽器登錄cookie

瀏覽器登錄cookie

事件 登陸 font lac check www rip style ntb



<!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">
//新建cookie。


//hours為空字符串時,cookie的生存期至瀏覽器會話結束。

hours為數字0時,建立的是一個失效的cookie,這個cookie會覆蓋已經建立過的同名、同path的cookie(假設這個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;
}
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;
//server驗證(模擬)
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("username或password錯誤。請又一次輸入!");
}
}

</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;">記住password</span>
<input id="saveCookie" type="checkbox" value="" /></p>
<p>
<input id="submit" type="button" value="GO" />
</p>
</form>
</body>
</html>

瀏覽器登錄cookie