简体   繁体   中英

How to get an objects back from cookies in javascript?

I'm kind of a beginner in javascript. I parsed my objects to store them in a cookie like this :

JSON.stringify(myObject)

but what do I do to turn the cookie's data back into my object? I'm missing something...

myObject=JSON.parse(myCookieData);

This is working now.

I'm still having a problem though: I store my cookie with onbeforeunload but it sometimes not store it. I tried with onunload too but I have the same problem. Does it take too much time to store the cookie? What is the problem?

Ok so I'm not using base64 anymore, just storing json'd objects in my cookie. My current problem is that the cookie is starting to grow in size badly... Sometimes it is too big to get stored.. How can I minimize the size?

I now use PersistJS . Thanks for your help.

Your code should work unless your 'myCookieData' isn't the actual portion of the cookie you care about.

For example try this in a browser console (javascript):

var foo = new Object();
foo.name = "Joe"
JSON.parse(JSON.stringify(foo))
> Object {name: "Joe"}

The result is an object as long as you have the correct 'myCookieData'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM