原生js登錄創建cookie


原生js創建cookie,功能:點擊登錄按鈕時,將用戶名、密碼存為cookie;頁面再次加載時,自動讀取cookie中的用戶名、密碼。

 

<html>
<head>
<title>cookies</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function setCookie(name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());//創建cookie
}

function getCookie(name)//獲取cookie
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(name + "=");
if (c_start!=-1)
{
c_start=c_start + 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 checkCookie()//檢查cookie是否存在,若存在,讀取出來
{
var userName=document.getElementById("userName");
var password=document.getElementById("password");
var UValue=getCookie(userName.id);
var PValue=getCookie(password.id);
if (UValue!=null && UValue!="" && PValue!=null && PValue!="")
{
userName.value=UValue;
password.value=PValue;
}
}

function saveCookie(){//保存cookie
var UName=document.getElementById("userName");
var PName=document.getElementById("password");
if(UName.value==""){
alert("請輸入用戶名!");
}
else if(PName.value==""){
alert("請輸入密碼!");
}
else if(confirm("是否保存用戶名密碼?")){
setCookie(UName.id,UName.value,30);
setCookie(PName.id,PName.value,30);
}
}
</script>
</head>

<body onload="checkCookie()">
<input id="userName" type="text" name="" placeholder="用戶名" value="">
<input id="password" type="password" name="" placeholder="密碼" value="">
<input type="button" name="" value="登錄" onclick="saveCookie()">
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM