頁面增加Cookie

weixin_34037515發表於2017-11-17

JSP頁面:

 

 

 

<table>

<tr>

<td>

<div>

<input id="UserID" class="text" type="text" tabindex="1"

placeholder="賬號" />

</div></td>

</tr>

<tr>

<td>

<div>

<input id="password" class="text" type="password"

placeholder="密碼" tabindex="2" />

</div></td>

</tr>

</table>

 

Js方法:

頁面載入完成後執行,從Cookie中獲取值,需要引入jquery.js

var   cookieValue   =   "";   

var   search   =   "user=";   

$(document).ready(function() {

 setTimeout('setvalue()',1000//1=1000,這裡是3

});

function setvalue(){

if(document.cookie.length   >   0)     {

offset   =   document.cookie.indexOf(search);

if(offset !=  -1){     

offset   +=   search.length;   

end   =   document.cookie.indexOf(";",offset);   

if   (end  ==  -1)   

end   =   document.cookie.length;

//獲取cookies裡面的值          

cookieValue   =   unescape(document.cookie.substring(offset,end))

if(cookieValue != null){

var str = cookieValue.split("/");


document.getElementById("UserID").value= str[0];

document.getElementById("password").value = str[1]; 

}

}   

}

進行登入操作時,儲存資訊到Cookie

//UserID,Password為使用者名稱密碼

function SetCookie(UserID,Password)//兩個引數,一個是cookie的名子,一個是值

{   

    var name = UserID;

    var password = Password;

    var Days = 7; //此 cookie 將被儲存 天 

    var exp  = new Date(); //生成一個現在的日期,加上儲存期限,然後設定cookie的生存期限!

    exp.setTime(exp.getTime() + Days*24*60*60*1000);

    document.cookie = "user="+ escape(name) + "/" + escape(password) + ";expires=" + exp.toGMTString();

}

//cookies函式--正規表示式(不會,學習正規表示式)  

function getCookie(name)      

{

    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));

    if(arr != nullreturn unescape(arr[2]); 

    return null;

}

刪除Cookie

function delCookie()

{

    var name = "admin";

    var exp = new Date();

    exp.setTime(exp.getTime() - 1);

    var cval=getCookie(name);

    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();

}



      本文轉自tianjian_0913 51CTO部落格,原文連結:http://blog.51cto.com/tianjian/1665998,如需轉載請自行聯絡原作者



相關文章