How do I create and read a value from cookie?

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

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

19条回答
  •  别跟我提以往
    2020-11-21 05:22

    For those who need save objects like {foo: 'bar'}, I share my edited version of @KevinBurke's answer. I've added JSON.stringify and JSON.parse, that's all.

    cookie = {
    
        set: function (name, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                var expires = "; expires=" + date.toGMTString();
            }
            else
                var expires = "";
            document.cookie = name + "=" + JSON.stringify(value) + expires + "; path=/";
        },
    
        get : function(name){
            var nameEQ = name + "=",
                ca = document.cookie.split(';');
    
            for(var i=0;i < ca.length;i++) {
              var c = ca[i];
              while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) 
                  return  JSON.parse(c.substring(nameEQ.length,c.length));
            }
    
            return null;
        }
    
    }
    

    So, now you can do things like this:

    cookie.set('cookie_key', {foo: 'bar'}, 30);
    
    cookie.get('cookie_key'); // {foo: 'bar'}
    
    cookie.set('cookie_key', 'baz', 30);
    
    cookie.get('cookie_key'); // 'baz'
    

提交回复
热议问题