纯 Javascript - 在 cookie 中存储对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11344531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pure Javascript - store object in cookie
提问by Shlomo
No jQuery.
没有jQuery。
I want to store an object or array in a cookie.
我想在 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.
我如何使用纯 JavaScript 做到这一点?我读了很多帖子,但不知道如何适当地连载。
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
?
我如何序列化
instances
?我如何维护功能,但更改实例的结构以能够序列化
stringify
?
回答by Beat Richartz
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:
然后转储数据,将其字符串化,将其写入 cookie,下次要使用它时,只需执行以下操作:
var mydata = JSON.parse(read_cookie('myinstances'));
new userConstructor(mydata.name, mydata.street, mydata.city);
回答by Oleg V. Volkov
Use either object's own .toString()
method if it gives meaningful serialization or JSON.stringify()
. Do note, however, that cookies are usually limited in length and won't be able to hold big amounts of data.
请使用对象自己的.toString()
,如果它给了有意义的序列或方法JSON.stringify()
。但请注意,cookie 通常长度有限,无法保存大量数据。
回答by Jean-Robin Tremblay
A cookie adaptation class from : http://www.sitepoint.com/cookieless-javascript-session-variables/
一个 cookie 适配类来自:http: //www.sitepoint.com/cookieless-javascript-session-variables/
All you need to do is to set and get variables you need to store in cookie.
您需要做的就是设置和获取需要存储在 cookie 中的变量。
Work with: int, string, array, list, Complex object
处理:整数、字符串、数组、列表、复杂对象
Exemple:
例子:
var toStore = Session.get('toStore');
if (toStore == undefined)
toStore = ['var','var','var','var'];
else
console.log('Restored from cookies'+toStore);
Session.set('toStore', toStore);
Class:
班级:
// Cross reload saving
if (JSON && JSON.stringify && JSON.parse) var Session = Session || (function() {
// session store
var store = load();
function load()
{
var name = "store";
var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
if (result)
return JSON.parse(result[1]);
return {};
}
function Save() {
var date = new Date();
date.setHours(23,59,59,999);
var expires = "expires=" + date.toGMTString();
document.cookie = "store="+JSON.stringify(store)+"; "+expires;
};
// page unload event
if (window.addEventListener) window.addEventListener("unload", Save, false);
else if (window.attachEvent) window.attachEvent("onunload", Save);
else window.onunload = Save;
// public methods
return {
// set a session variable
set: function(name, value) {
store[name] = value;
},
// get a session value
get: function(name) {
return (store[name] ? store[name] : undefined);
},
// clear session
clear: function() { store = {}; }
};
})();
回答by Clément Andraud
If you can serialize your object into its canonical string representation, and can unserialize it back into its object form from said string representation, then yes you can put it into a cookie.
如果您可以将对象序列化为其规范字符串表示形式,并且可以将其从所述字符串表示形式反序列化回其对象形式,那么是的,您可以将其放入 cookie 中。