【问题标题】:Pure Javascript - store object in cookie纯 Javascript - 将对象存储在 cookie 中
【发布时间】:2023-03-15 05:32:01
【问题描述】:

没有 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 进行序列化?

【问题讨论】:

  • 将对象转换为json并存储在cookie中。
  • stringify 不起作用。我得到TypeError: Converting circular structure to JSON 我的代码是:var instances = {}; instances[strInstanceId].plugin = oPlugin; ...

标签: javascript object cookies


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      试着写一个

      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);
      

      【讨论】:

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

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

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

      使用:int、字符串、数组、列表、复杂对象

      示例:

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

      【讨论】:

        猜你喜欢
        • 2011-09-30
        • 2023-03-04
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2011-04-28
        • 1970-01-01
        • 2010-12-19
        • 1970-01-01
        相关资源
        最近更新 更多