首页 > 技术文章 > coding++:js简单操作cookie

codingmode 2019-06-12 11:14 原文

1):引入 jquery.cookie.js 

/*!
 * jQuery Cookie Plugin v1.4.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2006, 2014 Klaus Hartl
 * Released under the MIT license
 */
(function(factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD (Register as an anonymous module)
        define([ 'jquery' ], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}
        (function($) {

            var pluses = /\+/g;

            function encode(s) {
                return config.raw ? s : encodeURIComponent(s);
            }

            function decode(s) {
                return config.raw ? s : decodeURIComponent(s);
            }

            function stringifyCookieValue(value) {
                return encode(config.json ? JSON.stringify(value)
                        : String(value));
            }

            function parseCookieValue(s) {
                if (s.indexOf('"') === 0) {
                    // This is a quoted cookie as according to RFC2068,
                    // unescape...
                    s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g,
                            '\\');
                }

                try {
                    // Replace server-side written pluses with spaces.
                    // If we can't decode the cookie, ignore it, it's unusable.
                    // If we can't parse the cookie, ignore it, it's unusable.
                    s = decodeURIComponent(s.replace(pluses, ' '));
                    return config.json ? JSON.parse(s) : s;
                } catch (e) {
                }
            }

            function read(s, converter) {
                var value = config.raw ? s : parseCookieValue(s);
                return $.isFunction(converter) ? converter(value) : value;
            }

            var config = $.cookie = function(key, value, options) {

                // Write

                if (arguments.length > 1 && !$.isFunction(value)) {
                    options = $.extend({}, config.defaults, options);

                    if (typeof options.expires === 'number') {
                        var days = options.expires, t = options.expires = new Date();
                        t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
                    }

                    return (document.cookie = [
                            encode(key),
                            '=',
                            stringifyCookieValue(value),
                            options.expires ? '; expires='
                                    + options.expires.toUTCString() : '', // use
                                                                            // expires
                                                                            // attribute,
                                                                            // max-age
                                                                            // is
                                                                            // not
                                                                            // supported
                                                                            // by
                                                                            // IE
                            options.path ? '; path=' + options.path : '',
                            options.domain ? '; domain=' + options.domain : '',
                            options.secure ? '; secure' : '' ].join(''));
                }

                // Read

                var result = key ? undefined : {},
                // To prevent the for loop in the first place assign an empty
                // array
                // in case there are no cookies at all. Also prevents odd result
                // when
                // calling $.cookie().
                cookies = document.cookie ? document.cookie.split('; ') : [], i = 0, l = cookies.length;

                for (; i < l; i++) {
                    var parts = cookies[i].split('='), name = decode(parts
                            .shift()), cookie = parts.join('=');

                    if (key === name) {
                        // If second argument (value) is a function it's a
                        // converter...
                        result = read(cookie, value);
                        break;
                    }

                    // Prevent storing a cookie that we couldn't decode.
                    if (!key && (cookie = read(cookie)) !== undefined) {
                        result[name] = cookie;
                    }
                }

                return result;
            };

            config.defaults = {};

            $.removeCookie = function(key, options) {
                // Must not alter options, thus extending a fresh object...
                $.cookie(key, '', $.extend({}, options, {
                    expires : -1
                }));
                return !$.cookie(key);
            };

        }));

2):引入 jquery.base64.js (这是自己写的 js )

(function ($) {

    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    $.extend({
        "Base64encode": function (e) {
            var t = "";
            var n, r, i, s, o, u, a;
            var f = 0;
            e = $.Base64_utf8_encode(e);
            while (f < e.length) {
                n = e.charCodeAt(f++);
                r = e.charCodeAt(f++);
                i = e.charCodeAt(f++);
                s = n >> 2;
                o = (n & 3) << 4 | r >> 4;
                u = (r & 15) << 2 | i >> 6;
                a = i & 63;
                if (isNaN(r)) {
                    u = a = 64
                } else if (isNaN(i)) {
                    a = 64
                }
                t = t + _keyStr.charAt(s) + _keyStr.charAt(o) + _keyStr.charAt(u) + _keyStr.charAt(a)
            }
            return t
        },
        "Base64decode": function (e) {
            var t = "";
            var n, r, i;
            var s, o, u, a;
            var f = 0;
            e = e.replace(/[^A-Za-z0-9+/=]/g, "");
            while (f < e.length) {
                s = _keyStr.indexOf(e.charAt(f++));
                o = _keyStr.indexOf(e.charAt(f++));
                u = _keyStr.indexOf(e.charAt(f++));
                a = _keyStr.indexOf(e.charAt(f++));
                n = s << 2 | o >> 4;
                r = (o & 15) << 4 | u >> 2;
                i = (u & 3) << 6 | a;
                t = t + String.fromCharCode(n);
                if (u != 64) {
                    t = t + String.fromCharCode(r)
                }
                if (a != 64) {
                    t = t + String.fromCharCode(i)
                }
            }
            t = $.Base64_utf8_decode(t);
            return t
        },
        "Base64_utf8_encode": function (e) {
            e = e.replace(/rn/g, "n");
            var t = "";
            for (var n = 0; n < e.length; n++) {
                var r = e.charCodeAt(n);
                if (r < 128) {
                    t += String.fromCharCode(r)
                } else if (r > 127 && r < 2048) {
                    t += String.fromCharCode(r >> 6 | 192);
                    t += String.fromCharCode(r & 63 | 128)
                } else {
                    t += String.fromCharCode(r >> 12 | 224);
                    t += String.fromCharCode(r >> 6 & 63 | 128);
                    t += String.fromCharCode(r & 63 | 128)
                }
            }
            return t
        },
        "Base64_utf8_decode": function (e) {
            var t = "";
            var n = 0;
            var r = c1 = c2 = 0;
            while (n < e.length) {
                r = e.charCodeAt(n);
                if (r < 128) {
                    t += String.fromCharCode(r);
                    n++
                } else if (r > 191 && r < 224) {
                    c2 = e.charCodeAt(n + 1);
                    t += String.fromCharCode((r & 31) << 6 | c2 & 63);
                    n += 2
                } else {
                    c2 = e.charCodeAt(n + 1);
                    c3 = e.charCodeAt(n + 2);
                    t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
                    n += 3
                }
            }
            return t
        }
    });
})(jQuery);

3):cookie_0.1.js  封装 (这是自己写的 js)

/**
 * 全局cookies操作
 */
(function ($) {

    /**
     * 设置cookie
     */
    $.setCookie = function (key, value, expires) {
        /*var  _key = $.base64.encode(encodeURIComponent(key));*/
        if (value) {
            if (typeof value == "object" || typeof value == "number") {
                value = JSON.stringify(value);
            }
            value = $.Base64encode(value);
        }
        var options = {path: '/'};
        if (expires) {
            options.expires = expires;
        }
        return $.cookie(key, value, options);
    };

    /**
     * 获取cookie
     */
    $.getCookie = function (key) {
        /*var _key = $.base64.encode(encodeURIComponent(key));*/
        var value = $.cookie(key);
        if (value) {
            value = $.Base64decode(value);
            value = decodeURIComponent(value);
            try {
                value = JSON.parse(value);
            } catch (e) {
            }
        }
        return value;
    };

    /**
     * 清理cookie
     */
    $.cleanCookie = function (key) {
        $.removeCookie(key, {path: '/'});
        return !$.cookie(key);
    };


}(jQuery));

4):使用  

CookieUtil:在 本博客 java 分类中 

    @RequestMapping("add")
    public String add(HttpServletResponse response) {
        CookieUtil.addCookie(response, "string", "string", 0);
        Map<String, String> map = new HashMap<String, String>() {{
            put("a", "a");
        }};
        CookieUtil.addCookie(response, "map", JSON.toJSONString(map), 0);
        return "OK";
    }

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CookiePage</title>
    <script src="/js/jquery-3.2.0.min.js"></script>
    <script type="text/javascript" src="/js/cookie/jquery.cookie.js"></script>
    <script src="/js/cookie/jquery.base64.js"></script>
    <script type="text/javascript" src="/js/cookie/cookie_0.1.js"></script>
</head>
<body>
<script type="text/javascript">

    $(function () {

        var _string = $.getCookie("string");
        var _map = $.getCookie("map");

        alert(_string + "--" + _map["a"]);
    });

</script>
</body>
</html>

 

通过上述编写 可读|可写|可删

 

推荐阅读