纯Javascript - 在Cookie中存储对象 [英] Pure Javascript - store object in cookie
问题描述
没有jQuery。
我想在cookie中存储对象或数组。
。
我如何使用纯JavaScript?我读了很多帖子,但不知道如何正确地序列化。
编辑:
代码: p>
var instances = {};
...
instances [strInstanceId] = {container:oContainer};
...
instances [strInstanceId] .plugin = oPlugin;
...
JSON.stringify(instances);
// throws error'TypeError:将循环结构转换为JSON'
-
如何序列化
实例
? -
如何维护功能,更改实例的结构以便能够使用
stringify
$ b序列化 h2_lin>解决方案
尝试写一个
function bake_cookie(name,value){
var cookie = [name,'=',JSON.stringify(value),'; domain =。',window.location.host.toString(),'; path = /;']。join('');
document.cookie = cookie;
}
阅读它:
$ b b
function read_cookie(name){
var result = document.cookie.match(new RegExp(name +'=([^;] +)'));
result&&& (result = JSON.parse(result [1]));
return result;
}
要删除它:
$ b b
function delete_cookie(name){
document.cookie = [name,'= expires = Thu,1970年1月1日00:00:01 GMT; path = /; domain =。',window.location.host.toString()]。join('');
}
为了序列化复杂的对象/实例,为什么不在你的实例:
function userConstructor(name,street,city){
// ...您的代码
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);
No jQuery.
I want to store an object or array in a cookie.
The object should be usable after page refresh.
How do I do that with pure JavaScript? I read many posts, but do not know how to serialize appropriately.
EDIT: Code:
var instances = {};
...
instances[strInstanceId] = { container: oContainer };
...
instances[strInstanceId].plugin = oPlugin;
...
JSON.stringify(instances);
// throws error 'TypeError: Converting circular structure to JSON'
How do I serialize
instances
?How do I maintain functionality, but change structure of instance to be able to serialize with
stringify
?
Try that one to write
function bake_cookie(name, value) {
var cookie = [name, '=', JSON.stringify(value), '; domain=.', window.location.host.toString(), '; path=/;'].join('');
document.cookie = cookie;
}
To read it take:
function read_cookie(name) {
var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
result && (result = JSON.parse(result[1]));
return result;
}
To delete it take:
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
}
}
}
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屋!