纯Javascript - 在cookie中存储对象

时间:2012-07-05 12:38:49

标签: javascript object cookies

没有jQuery。

我想将一个对象或数组存储在cookie中。

页面刷新后该对象应该可用。

如何使用纯JavaScript实现这一目标?我阅读了很多帖子,但不知道如何正确序列化。


编辑: 代码:

var instances = {};
...
instances[strInstanceId] = { container: oContainer };
...
instances[strInstanceId].plugin = oPlugin;
...
JSON.stringify(instances); 
// throws error 'TypeError: Converting circular structure to JSON'
  1. 如何序列化instances

  2. 如何维护功能,但更改实例的结构以便能够使用stringify进行序列化?

4 个答案:

答案 0 :(得分:50)

尝试写一个

function bake_cookie(name, value) {
  var cookie = [name, '=', JSON.stringify(value), '; domain=.', window.location.host.toString(), '; path=/;'].join('');
  document.cookie = cookie;
}

要阅读它:

function read_cookie(name) {
 var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
 result && (result = JSON.parse(result[1]));
 return result;
}

删除它需要:

function delete_cookie(name) {
  document.cookie = [name, '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.', window.location.host.toString()].join('');
}

要序列化复杂对象/实例,为什么不在实例中编写数据转储函数:

function userConstructor(name, street, city) {
   // ... your code
   this.dumpData = function() {
     return {
        'userConstructorUser': {
            name: this.name,
            street: this.street,
            city: this.city
         }
       }
    }

然后你转储数据,将其串化,将其写入cookie,下次你想使用它时,只需去:

  var mydata = JSON.parse(read_cookie('myinstances'));
  new userConstructor(mydata.name, mydata.street, mydata.city);

答案 1 :(得分:3)

如果对象具有有意义的序列化或.toString(),则使用对象自己的JSON.stringify()方法。但请注意,cookie的长度通常有限,并且无法保存大量数据。

答案 2 :(得分:3)

来自以下的cookie改编课程: http://www.sitepoint.com/cookieless-javascript-session-variables/

您需要做的就是设置并获取需要存储在cookie中的变量。

使用:int,string,array,list,Complex object

例:

var toStore =  Session.get('toStore');

if (toStore == undefined)
    toStore = ['var','var','var','var'];
else
    console.log('Restored from cookies'+toStore);

Session.set('toStore', toStore);

类别:

// Cross reload saving
if (JSON && JSON.stringify && JSON.parse) var Session = Session || (function() {
// session store

var store = load();

function load()
{
    var name = "store";
    var result = document.cookie.match(new RegExp(name + '=([^;]+)'));

    if (result)
        return JSON.parse(result[1]);

    return {};
}

function Save() {
    var date = new Date();
    date.setHours(23,59,59,999);
    var expires = "expires=" + date.toGMTString();
    document.cookie = "store="+JSON.stringify(store)+"; "+expires;
};

// page unload event
if (window.addEventListener) window.addEventListener("unload", Save, false);
else if (window.attachEvent) window.attachEvent("onunload", Save);
else window.onunload = Save;

// public methods
return {

    // set a session variable
    set: function(name, value) {
        store[name] = value;
    },

    // get a session value
    get: function(name) {
        return (store[name] ? store[name] : undefined);
    },

    // clear session
    clear: function() { store = {}; }
};
})();

答案 3 :(得分:2)

如果您可以将对象序列化为其规范字符串表示形式,并且可以从所述字符串表示形式将其反序列化为其对象形式,则可以将其放入cookie中。

相关问题