纯 Javascript - 在 cookie 中存储对象 [英] Pure Javascript - store object in cookie
问题描述
没有jQuery.
我想在 cookie 中存储一个对象或数组.
I want to store an object or array in a cookie.
该对象应该在页面刷新后可用.
The object should be usable after page refresh.
如何使用纯 JavaScript 做到这一点?看了很多帖子,不知道怎么连载.
How do I do that with pure JavaScript? I read many posts, but do not know how to serialize appropriately.
代码:
var instances = {};
...
instances[strInstanceId] = { container: oContainer };
...
instances[strInstanceId].plugin = oPlugin;
...
JSON.stringify(instances);
// throws error 'TypeError: Converting circular structure to JSON'
如何序列化
instances
?
如何维护功能,但更改实例结构以能够使用 stringify
进行序列化?
How do I maintain functionality, but change structure of instance to be able to serialize with stringify
?
推荐答案
试试那个写
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('');
}
要序列化复杂的对象/实例,为什么不在您的实例中编写数据转储函数:
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
}
}
}
然后转储数据,将其字符串化,将其写入 cookie,下次您想使用它时就去:
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);
这篇关于纯 Javascript - 在 cookie 中存储对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!