首頁  >  文章  >  web前端  >  javascript操作cookie的教學實例

javascript操作cookie的教學實例

零下一度
零下一度原創
2017-06-28 14:12:20915瀏覽

cookie

cookie,有時也用其複數形式Cookies,指某些網站為了辨別使用者身分、進行session追蹤而儲存在使用者本地端上的資料(通常經過加密)。定義於RFC2109和2965都已廢棄,最新取代的規範是RFC6265。

cookie的作用

伺服器可以利用Cookies包含資訊的任意性來篩選並經常性維護這些訊息,以判斷在HTTP傳輸中的狀態。 Cookies最典型的應用是判定註冊用戶是否已 經登入網站,用戶可能會得到提示,是否在下次進入此網站時保留用戶資訊以便簡化登入手續,這些都是Cookies的功用。另一個重要應用場合是「購物 車」之類處理。使用者可能會在一段時間內在同一家網站的不同頁面中選擇不同的商品,這些資訊都會寫入Cookies,以便在最後付款時提取資訊。

js設定cookie

document.cookie="popped=yes"

js取得cookie

function get_cookie (Name) {   var search = Name + "="//查詢擷取的值  var returnvalue = "";//回傳值  if (document.cookie.length > 0) {     sd = document.cookie.indexOf(search);     if (sd!= -1) {        sd += search.length;        end = document.cookie.indexOf(";", sd);        if (end == -1)         end = document.cookie.length;
        //unescape() 函數可對透過 escape() 編碼的字串進行解碼。        returnvalue=unescape(document.cookie.substring(sd, end))      }   }   return returnvalue; }
//使用方式:
get_cookie("popped");

給cookie設定終止日期

例如:如果要將cookie設定為10天後過期,可以這樣實作:

//取得目前時間var date=new Date();var expiresDays=10;//將date設為10天以後的時間date.setTime(date.getTime()+expiresDays*24*3600*1000);//將userId和userName兩個cookie設定為10天後過期document.cookie="userId=828; userName=hulk; expires= "+date.toGMTString();

其中GMT_String是以GMT格式表示的時間字串,這條語句就是將userId這個cookie設定為GMT_String表示的過期時間,超過這個時間,cookie將消失,不可進入。

刪除cookie 
為了刪除一個cookie,可以將其過期時間設定為一個過去的時間,例如:

//取得目前時間var date=new Date(); //將date設定為過去的時間date.setTime(date.getTime()-10000);//將userId這個cookie刪除document.cookie="userId=828; expires="+date.toGMTString();

下面封裝上面的方法

#

var cookie = {    set:function(key,val,time){//設定cookie方法        var date=new Date(); //取得目前時間        var expiresDays=time;  //將date設定為n天以後的時間        date.setTime(date.getTime()+expiresDays*24*3600*1000); //格式化為cookie辨識的時間        document.cookie=key + "=" + val +";expires="+date.toGMTString();  //設定cookie    },    get:function(key){//取得cookie方法        /*取得cookie參數*/        var getCookie = document.cookie.replace(/[ ]/g,"");  //取得cookie,並且將獲得的cookie格式化,去除空格字符        var arrCookie = getCookie.split(";")  //將所得的cookie以"分號"為標識 將cookie儲存到arrCookie的陣列中        var tips;  //宣告變數tips        for(var i=0;i      delete:function(key){ //刪除cookie方法
        var date = new Date(); //取得目前時間
        date.setTime(date.getTime(date.getTime()-10000) 0/0000); /將date設定為過去的時間
        document.cookie = key + "=v; expires =" +date.toGMTString();//設定cookie
      }       } }

使用方式:

cookie.set("uesr","sss",24);//設定為24天過期
alert(cookie .get("uesr"));//取得cookie


以上是javascript操作cookie的教學實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn