天天看點

頁面增加Cookie

<table>

<tr>

<td>

<div>

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

placeholder="賬号" />

</div></td>

</tr>

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

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

</table>

頁面加載完成後執行,從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 将被儲存 7 天 

    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 != null) return 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,如需轉載請自行聯系原作者

下一篇: nginx

繼續閱讀