纯 Javascript - 在 cookie 中存储对象

IT技术 javascript object cookies
2021-02-18 12:03:53

没有 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个回答

试试那个写

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);
... 一个太大的 cookie 可能会导致用户永久站点故障,而您却没有注意到,因为 Upstream 标头太大。我编辑了我的帖子,所以你可以看到我上面评论的意思。
2021-04-20 12:03:53
谢谢 如果我开始stringify工作,我会去的。你能检查我的代码问题吗?
2021-04-26 12:03:53
我不明白您对转储功能的回答。该变量instances包含 2 个导致此错误的对象,一个是 ExtJS,另一个是 DeftJS 对象。我怎样才能序列化这些?你能解释一下吗?
2021-04-28 12:03:53
JSON 无法序列化整个实例,但您可以序列化您可能需要的来自这些实例的任何相关数据,并使用此保存的数据重新初始化它们。例如,您有一个 name = 'John Doe' 的实例,您可以在该实例上编写一个函数来返回一个像 {myinstance: {name: 'John Doe'}} 这样的对象,然后使用此数据再次调用构造函数. 除此之外,您可以尝试使用 GSerializer:onegeek.com.au/projects/javascript-serialization(关于此的好帖子)但我建议不要这样做,因为 Cookie 的大小有限...
2021-04-29 12:03:53
每个 JS 实例中通常都有两种类型的数据:属性函数我的评论想说的是,将函数存储在 cookie 中是没有用的,因为这些函数通常不会更改。您应该提取属性并将它们写入 cookie,因为存储大型实例的实例(我猜测以某种方式字符串化的 ExtJS 和 DeftJS 实例会很大)不适合 cookie(大小限制为 4KB,本质上)。 .
2021-05-03 12:03:53

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

一个 cookie 适配类来自:http : //www.sitepoint.com/cookieless-javascript-session-variables/

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

处理:整数、字符串、数组、列表、复杂对象

例子:

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

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

Session.set('toStore', toStore);

class:

// 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 = {}; }
};
})();

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