简体   繁体   English

如何从JavaScript的Cookie中获取对象?

[英]How to get an objects back from cookies in javascript?

I'm kind of a beginner in javascript. 我有点喜欢javascript。 I parsed my objects to store them in a cookie like this : 我解析了对象,将其存储在这样的cookie中:

JSON.stringify(myObject)

but what do I do to turn the cookie's data back into my object? 但是我该怎么做才能将cookie的数据转回到我的对象中呢? 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. 我仍然有一个问题:我使用onbeforeunload存储我的cookie,但有时不存储它。 I tried with onunload too but I have the same problem. 我也尝试过onunload但是我有同样的问题。 Does it take too much time to store the cookie? 存储cookie是否花费太多时间? What is the problem? 问题是什么?

Ok so I'm not using base64 anymore, just storing json'd objects in my cookie. 好的,所以我不再使用base64,只是将json'd对象存储在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? 我当前的问题是cookie的大小开始严重增长。有时它太大而无法存储。如何缩小大小?

I now use PersistJS . 我现在使用PersistJS Thanks for your help. 谢谢你的帮助。

Your code should work unless your 'myCookieData' isn't the actual portion of the cookie you care about. 除非您的“ myCookieData”不是您关心的cookie的实际部分,否则您的代码应该可以工作。

For example try this in a browser console (javascript): 例如,在浏览器控制台(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' 只要您具有正确的“ myCookieData”,结果就是一个对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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