js操作cookie

來源:互聯網
上載者:User

標籤:date   log   etc   value   目前時間   expired   com   htm   cookies   

js本地化操作,設定cookie、擷取cookie,刪除cookie的例子:

參考網站:w3c js操作cookie

代碼:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body><button id="btn1" onclick="setCookies()">設定cookies</button><button id="btn2" onclick="getCookies()">讀取cookies</button><button id="btn3" onclick="clearCookies()">清除cookies</button></body><script type="text/javascript">function setCookies(){    setCookie(‘name‘, ‘zhangsan‘);    setCookie(‘password‘, ‘123456‘, 2);    setCookie(‘age‘, ‘12‘);}function getCookies(){    var name = getCookie(‘name‘);    var password = getCookie(‘password‘);    var age = getCookie(‘age‘);    console.log("name:"+name+" password:"+password+" age:"+age);}function clearCookies(){    deleteCookie(‘name‘);    deleteCookie(‘age‘);    deleteCookie(‘password‘);}/** * 設定cookie 索引值對形式 * name 儲存的key * value 對應的值 * expiredays 到期時間 天數  如果為null的話不設定到期時間 * 不設定這個值的話,cookie預設在關閉瀏覽器時失效 */function setCookie(name, value, expiredays){    var exdate=new Date();    if(expiredays==null || typeof(expiredays)==‘undefined‘){        document.cookie = name + "="+escape(value);    }else{        exdate.setDate(exdate.getDate()+expiredays);        document.cookie = name + "="+escape(value)+";expires="+exdate.toGMTString();    }}/** * 讀取cookie */ function getCookie(name){    if(document.cookie.length>0){        var start = document.cookie.indexOf(name + "=");        if(start != -1){            start = start + name.length + 1;            end = document.cookie.indexOf(";",start);            if(end == -1){                end = document.cookie.length;            }            return unescape(document.cookie.substring(start, end));        }    }    return null;}/** * 刪除cookie */ function deleteCookie(name){    var exp = new Date();    exp.setTime(exp.getTime() - 1000); //目前時間減去一秒,相當於立即到期(可以增減)    var val = getCookie(name);    if(val!=null){        document.cookie = name + "="+val+";expires="+exp.toGMTString();    }}</script></html>
password設定了到期時間,看設定到期時間與不設定到期時間的區別:


 

 

js操作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.