cookie

 

 cookie

 cookie
 
  • 服務器用來在客戶端存儲一些數據,好比用戶信息
  • 量小 4kb
  • 1-設置cookie
     document.cookie = "username=aaa";
            document.cookie = "pass=123";
            var date = new Date();
            date.setSeconds(date.getSeconds() + 10);
            //設置cookie 及過時時間
            //document.cookie = "username=aaa;expires=" + date;
            
            封裝設置cookie方法:
            function setCookie(cName, cValue, day) {
                var date = new Date();
                date.setDate(date.getDate() + day);
                document.cookie = cName + '=' + cValue + ';expires=' + date;
            }
            setCookie('username', 'aaa', 1);
            setCookie('pass', '123', 1);
  • 2-獲取cookie
      var c = document.cookie;
        console.log(c); //'username=aaa; pass=123'
    
        封裝獲取cookie的方法:
        function getCookie(cName) {
            var cookieObj = {};
            var cstring = document.cookie; //'username=aaa; pass=123; city=bbb'  --> {username:aaa,pass:123}
            var ary = cstring.split('; '); //['username=aaa','pass=123']
            for (var i = 0; i < ary.length; i++) {
                var ary1 = ary[i].split('=');
                cookieObj[ary1[0]] = ary1[1];
            }
            return cookieObj[cName];
        }
    
        var v = getCookie('pass');
        console.log(v);
  • 3-刪除cookie
        /* 刪除cookie :原理就是把過時時間設置爲前一天*/
        function removeCookie(cName) {
            setCookie(cName, 1, -1);
        }
        removeCookie('username');

     

參考資料:  https://www.cnblogs.com/bq-med/p/8603664.htmlhtml

相關文章
相關標籤/搜索