没有 jQuery。
我想在 cookie 中存储一个对象或数组。
页面刷新后该对象应该可用。
我如何使用纯 JavaScript 来做到这一点?看了很多帖子,不知道怎么连载。
编辑: 代码:
var instances = {};
...
instances[strInstanceId] = { container: oContainer };
...
instances[strInstanceId].plugin = oPlugin;
...
JSON.stringify(instances);
// throws error 'TypeError: Converting circular structure to JSON'
如何序列化
实例
?如何保持功能,但更改实例的结构以便能够使用
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('');
}
要序列化复杂的对象/实例,为什么不在你的实例中写一个数据转储函数:
function userConstructor(name, street, city) {
// ... your code
this.dumpData = function() {
return {
'userConstructorUser': {
name: this.name,
street: this.street,
city: this.city
}
}
}
然后你转储数据,将其字符串化,将其写入 cookie,下次你想使用它时:
var mydata = JSON.parse(read_cookie('myinstances'));
new userConstructor(mydata.name, mydata.street, mydata.city);
关于javascript - 纯 Javascript - 在 cookie 中存储对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11344531/