Shl*_*omo 36 javascript cookies object
没有jQuery.
我想将一个对象或数组存储在cookie中.
页面刷新后该对象应该可用.
我如何使用纯JavaScript做到这一点?我阅读了很多帖子,但不知道如何正确序列化.
编辑:代码:
var instances = {};
...
instances[strInstanceId] = { container: oContainer };
...
instances[strInstanceId].plugin = oPlugin;
...
JSON.stringify(instances);
// throws error 'TypeError: Converting circular structure to JSON'
Run Code Online (Sandbox Code Playgroud)
我该如何序列化instances
?
如何维护功能,但改变实例的结构以便能够序列化stringify
?
Bea*_*rtz 59
试试那个写
function bake_cookie(name, value) {
var cookie = [name, '=', JSON.stringify(value), '; domain=.', window.location.host.toString(), '; path=/;'].join('');
document.cookie = cookie;
}
Run Code Online (Sandbox Code Playgroud)
阅读它需要:
function read_cookie(name) {
var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
result && (result = JSON.parse(result[1]));
return result;
}
Run Code Online (Sandbox Code Playgroud)
删除它需要:
function delete_cookie(name) {
document.cookie = [name, '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.', window.location.host.toString()].join('');
}
Run Code Online (Sandbox Code Playgroud)
要序列化复杂对象/实例,为什么不在实例中编写数据转储函数:
function userConstructor(name, street, city) {
// ... your code
this.dumpData = function() {
return {
'userConstructorUser': {
name: this.name,
street: this.street,
city: this.city
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你转储数据,将其串化,写入cookie,下次你想使用它时,只需:
var mydata = JSON.parse(read_cookie('myinstances'));
new userConstructor(mydata.name, mydata.street, mydata.city);
Run Code Online (Sandbox Code Playgroud)
小智 6
一个 cookie 适配类来自:http : //www.sitepoint.com/cookieless-javascript-session-variables/
您需要做的就是设置和获取需要存储在 cookie 中的变量。
处理:整数、字符串、数组、列表、复杂对象
例子:
var toStore = Session.get('toStore');
if (toStore == undefined)
toStore = ['var','var','var','var'];
else
console.log('Restored from cookies'+toStore);
Session.set('toStore', toStore);
Run Code Online (Sandbox Code Playgroud)
班级:
// 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 = {}; }
};
})();
Run Code Online (Sandbox Code Playgroud)