javascript 設定cookie和取得cookie

來源:互聯網
上載者:User

標籤:tle   charset   color   val   9.png   throw   substr   utf-8   src   

代嗎執行個體:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>cookie</title>    <script>        function  setCookie(name,value,expires,path,domain,secure)  {            var cookieName=encodeURIComponent(name)+‘=‘+encodeURIComponent(value);            if(expires instanceof Date ) {                cookieName+=‘;expires=‘+expires;            }            if(path) {                cookieName+=‘;path=‘+path;            }            if(domain) {domain                cookieName+=‘;domain=‘+domain;            }            if(secure) {                cookieName+=‘;secure‘;            }            document.cookie=cookieName;        }        function  getCookie(name) {            var cookieName=encodeURIComponent(name)+‘=‘;            var cookieStart = document.cookie.indexOf(cookieName);            if (cookieStart>-1) {                var cookieEnd=document.cookie.indexOf(‘;‘,cookieStart);                if(cookieEnd==-1){                    cookieEnd=documet.cookie.length;                }                cookieValue=decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd));                return   cookieValue;            }        }        alert(getCookie(‘user‘));        alert(getCookie(‘email‘));        alert(getCookie(‘url‘));        function setCookieDate(day) {            //傳遞一個天數,比如傳遞7,就7天后失效            var date = null;            if (typeof day == ‘number‘ && day > 0) {                date = new Date();                date.setDate(date.getDate() + day);            } else {                throw new Error(‘您傳遞的天數不合法!必須是數字且大於0‘);            }            return date;        }</script></head><p>設定cookie和取得cookie </p></body></html>

效果:

設定cookie

Firefox設定下隱私選項我們可以看到cookie,在localhost中我們可以看到結果。

 cookie 中的user

 

 cookie 中的url

cookie 中的email

 

取得cookie

 

 

 

16:45:06   2017-09-04

javascript 設定cookie和取得cookie

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.