Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

Pure Javascript - store object in cookie

No jQuery.

I want to store an object or array in a cookie.

The object should be usable after page refresh.

How do I do that with pure JavaScript? I read many posts, but do not know how to serialize appropriately.


EDIT: Code:

var instances = {};
...
instances[strInstanceId] = { container: oContainer };
...
instances[strInstanceId].plugin = oPlugin;
...
JSON.stringify(instances); 
// throws error 'TypeError: Converting circular structure to JSON'
  1. How do I serialize instances?

  2. How do I maintain functionality, but change structure of instance to be able to serialize with stringify?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try that one to write

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

To read it take:

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

To delete it take:

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

To serialize complex objects / instances, why not write a data dump function in your instance:

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

Then you dump the data, stringify it, write it to the cookie, and next time you want to use it just go:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...