zoukankan      html  css  js  c++  java
  • 【javascript】cookie

    一、什么是 cookie?

    cookie 就是页面用来保存信息,比如自动登录、记住用户名等等。

    二、cookie 的特点

    1. 同个网站中所有的页面共享一套 cookie
    2. cookie 有数量、大小限制
    3. cookie 有过期时间

    三、如何使用 cookie?

    通过 document.cookie 来写入 cookie

    <!DOCTYPE HTML>
    <html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <title>cookie基础</title>
    </head>
    <body>
        
    </body>
    </html>
    <script type="text/javascript">
    document.cookie = 'username=abc';
    document.cookie = 'password=123';
    document.cookie = 'email=abcdef@123.com';
    </script>

    打开浏览器查看 cookie,可以发现新定义的 cookie 并不会将原来的覆盖。

    如果没有设置过期时间,那么关闭浏览器就会清空 cookie。如何设置过期时间呢?答案是:expires。一般我们会结合 Date 对象来使用。

    var d = new Date();
    d.setTime(d.getTime() + 1 * 3600 * 1000);
    document.cookie = 'username=abc; expires=' + d.toGMTString();

    我们可以通过火狐浏览器看到,username 的过期时间是当前时间的 1 小时后。

    最后对获取 cookie 的方法进行封装:

    function setCookie(name,value,hours){  
        var d = new Date();
        d.setTime(d.getTime() + hours * 3600 * 1000);
        document.cookie = name + '=' + value + '; expires=' + d.toGMTString();
    }

    学会了如何设置 cookie,那么该如何读取 cookie 呢?

    首先我们看下 cookie 里的内容是什么类型?

    document.cookie = 'username=abc';
    document.cookie = 'password=123';
    document.cookie = 'email=abcdef@123.com';
    typeof document.cookie;    //string
    alert(document.cookie);    //'username=abc; password=123; email=abcdef@123.com'

    得到的是一串字符串,需要注意的是,每个 ; 后面都有个空格。

    那么我们如何取到具体的数值呢?附上代码:

    function getCookie(name){  
        var arr = document.cookie.split('; ');
        for(var i = 0; i < arr.length; i++){
            var temp = arr[i].split('=');
            if(temp[0] == name){
                return temp[1];
            }
        }
        return '';
    }

    除了设置、获取 cookie,我们还可以删除 cookie。我们在网上经常看到有清除用户名这样的功能,其实就是用到了清除 cookie。

    清除 cookie 其实很简单,只要使过期时间为过去时间就可以了。

    function removeCookie(name){
        var d = new Date();
        d.setTime(d.getTime() - 10000);
        document.cookie = name + '=1; expires=' + d.toGMTString();
    }

    最后我们将设置、获取、清除 cookie 封装成一个 cookie.js

    function setCookie(name,value,hours){  
        var d = new Date();
        d.setTime(d.getTime() + hours * 3600 * 1000);
        document.cookie = name + '=' + value + '; expires=' + d.toGMTString();
    }
    function getCookie(name){  
        var arr = document.cookie.split('; ');
        for(var i = 0; i < arr.length; i++){
            var temp = arr[i].split('=');
            if(temp[0] == name){
                return temp[1];
            }
        }
        return '';
    }
    function removeCookie(name){
        var d = new Date();
        d.setTime(d.getTime() - 10000);
        document.cookie = name + '=1; expires=' + d.toGMTString();
    }

    PS:附上 cookie 应用的小实例。点击这里

    更新(2017-02-02)

    function cookie(name, value, opts) {
        if (typeof value !== 'undefined') {
            var expires = '';
            opts = opts || {};
            if (value === null) {
                value = '';
                opts.expires = -1;
            }
            if (opts.expires) {
                var date = new Date();
                date.setTime(date.getTime() + (opts.expires * 60 * 60 * 1000));
                expires = '; expires=' + date.toGMTString();
            }
            var path = opts.path ? '; path=' + opts.path : '';
            var domain = opts.domain ? '; domain=' + opts.domain : '';
            var secure = opts.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else {
            var cookies;
            if (document.cookie && document.cookie !== '') {
                cookies = document.cookie.match(new RegExp('(^| )' + name + '=([^;]*)(;|$)'));
                if (cookies) {
                    return decodeURIComponent(cookies[2]);
                } else {
                    return null;
                }
            }
        }
    }

    参数说明:

    • name:读取/写入/删除 cookie 的名称
    • value:需要设置 cookie 的值
    • opts:其他参数,有效期 expires 单位小时,路径 path,域名 domain,安全性 secure
    • 返回值:有 cookie 就返回 cookie 的值,没有返回 null

    使用方法:

    cookie('name', 'zhuyujia');
    cookie('age', 29, {expires: 1});
    cookie('name');    //'zhuyujia'
    cookie('age');    //29

    只需要设置 cookie 的值为 null,就可以删除相应的 cookie 了。

    cookie('name', null);
    cookie('age', null);
  • 相关阅读:
    datetime模块
    python正则表达式练习题
    Python入门——turtle库的使用
    Python入门——Python程序语法元素
    Python入门——eval() 函数
    Python入门——实例1_温度转换
    Python入门——编程方式
    Python入门——程序的基本编写方法
    Python入门——编译和解释
    SQL中isnull、ifnull和nullif函数用法
  • 原文地址:https://www.cnblogs.com/yjzhu/p/2789032.html
Copyright © 2011-2022 走看看