嘗試一個寫
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);
['JSON.stringify()'](HTTPS: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify)它。 – Matt 2012-07-05 12:40:08
將對象轉換爲json並將其存儲在cookie中。 – 2012-07-05 12:40:47
'stringify'不起作用。我得到'TypeError:將圓形結構轉換爲JSON'我的代碼是:var instances = {};實例[strInstanceId] .plugin = oPlugin; ...' – Patrick 2012-07-05 14:00:10