How do I create and read a value from cookie?

前端 未结 19 1624
梦如初夏
梦如初夏 2020-11-21 04:42

How can I create and read a value from a cookie in JavaScript?

19条回答
  •  情书的邮戳
    2020-11-21 04:55

    I use this object. Values are encoded, so it's necessary to consider it when reading or writing from server side.

    cookie = (function() {
    
    /**
     * Sets a cookie value. seconds parameter is optional
     */
    var set = function(name, value, seconds) {
        var expires = seconds ? '; expires=' + new Date(new Date().getTime() + seconds * 1000).toGMTString() : '';
        document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
    };
    
    var map = function() {
        var map = {};
        var kvs = document.cookie.split('; ');
        for (var i = 0; i < kvs.length; i++) {
            var kv = kvs[i].split('=');
            map[kv[0]] = decodeURIComponent(kv[1]);
        }
        return map;
    };
    
    var get = function(name) {
        return map()[name];
    };
    
    var remove = function(name) {
        set(name, '', -1);
    };
    
    return {
        set: set,
        get: get,
        remove: remove,
        map: map
    };
    
    })();
    

提交回复
热议问题