• js操作cookie


    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设置了过期时间,看设置过期时间与不设置过期时间的区别:

    
    
    
  • 相关阅读:
    【RL-TCPnet网络教程】第41章 HTTP超文本传输协议基础知识
    【安富莱TCPnet网络教程】HTTP通信实例
    【原创开源】网络版二代双通道示波器开源发布,支持电脑,手机和Pad等各种OS平台访问
    【RL-TCPnet网络教程】第40章 RL-TCPnet之TFTP客户端(精简版)
    【RL-TCPnet网络教程】第38章 TFTP简单文件传输基础知识
    linux添加环境变量
    linux字体安装
    lsof常用命令
    systemctl
    简单磁盘操作
  • 原文地址:https://www.cnblogs.com/tenWood/p/6725878.html
Copyright © 2020-2023  润新知