Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 在sessionStorage中保存Javascript对象(Save Javascript objects in sessionStorage)

SessionStorage and LocalStorage allows to save key/value pairs in a web browser.

(SessionStorage和LocalStorage允许在Web浏览器中保存键/值对。)

The value must be a string, and save js objects is not trivial.

(该值必须是一个字符串,并且保存js对象并不简单。)

var user = {'name':'John'};
sessionStorage.setItem('user', user);
var obj = sessionStorage.user; // obj='[object Object]' Not an object

Nowadays, you can avoid this limitation by serializing objects to JSON, and then deserializing them to recover the objects.

(现在,您可以通过将对象序列化为JSON,然后反序列化它们来恢复对象来避免此限制。)

But the Storage API always pass through the setItem and getItem methods.

(但Storage API始终通过setItemgetItem方法。)

sessionStorage.setItem('user', JSON.stringify(user));
var obj = JSON.parse(sessionStorage.getItem('user')); // An object :D

Can I avoid this limitation?

(我可以避免这种限制吗?)

I just want to execute something like this:

(我只是想执行这样的事情:)

sessionStorage.user.name; // 'John'
sessionStorage.user.name = 'Mary';
sessionStorage.user.name // 'Mary'

I have tried the defineGetter and defineSetter methods to intercept the calls but its a tedious job, because I have to define all properties and my target is not to know the future properties.

(我已经尝试使用defineGetterdefineSetter方法来拦截调用,但这是一项繁琐的工作,因为我必须定义所有属性,而我的目标是不知道未来的属性。)

  ask by Ferran Basora translate from so

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

1 Answer

0 votes
by (71.8m points)

Could you not 'stringify' your object...then use sessionStorage.setItem() to store that string representation of your object...then when you need it sessionStorage.getItem() and then use $.parseJSON() to get it back out?

(你能否“对字符串化”你的对象...然后使用sessionStorage.setItem()来存储你的对象的字符串表示...然后当你需要它时sessionStorage.getItem()然后使用$.parseJSON()来获取它退出?)

Working example http://jsfiddle.net/pKXMa/

(工作示例http://jsfiddle.net/pKXMa/)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...