2012-07-05 87 views
30

沒有jQuery。純Javascript - 在cookie中存儲對象

我想將對象或數組存儲在cookie中。

該對象在頁面刷新後應該可用。

我如何用純JavaScript做到這一點?我閱讀了很多帖子,但不知道如何正確序列化。


編輯: 代碼:

var instances = {}; 
... 
instances[strInstanceId] = { container: oContainer }; 
... 
instances[strInstanceId].plugin = oPlugin; 
... 
JSON.stringify(instances); 
// throws error 'TypeError: Converting circular structure to JSON' 
  1. 如何序列instances

  2. 如何維護功能,但更改實例的結構以便能夠使用stringify進行序列化?

+4

['JSON.stringify()'](HTTPS: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify)它。 – Matt 2012-07-05 12:40:08

+0

將對象轉換爲json並將其存儲在cookie中。 – 2012-07-05 12:40:47

+0

'stringify'不起作用。我得到'TypeError:將圓形結構轉換爲JSON'我的代碼是:var instances = {};實例[strInstanceId] .plugin = oPlugin; ...' – Patrick 2012-07-05 14:00:10

回答

45

嘗試一個寫

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); 
+0

謝謝如果我使用'stringify'工作,那麼我就去。你能檢查我的代碼問題嗎? – Patrick 2012-07-05 14:39:17

+0

JSON無法序列化整個實例,但可以序列化您可能希望從這些實例獲得的任何相關數據,並使用此保存的數據重新初始化它們。例如,您有一個名爲'John Doe'的實例,您可以在該實例上編寫一個函數來返回一個對象,例如{myinstance:{name:'John Doe'}},然後再次使用此數據調用構造函數。除此之外,你可以嘗試GSerializer:http://www.onegeek.com.au/projects/javascript-serialization(好帖子)但我會建議不要這樣做,因爲Cookie的大小是有限的...... – 2012-07-05 15:48:10

+0

。 ..並且cookie太大可能會導致用戶永久性站點故障,因爲上游標頭太大而無法通知您。我編輯了我的帖子,以便您能夠看到我上面評論的含義。 – 2012-07-05 15:49:20

2

如果你可以序列化你的對象到其規範的字符串表示,並且可以反序列化它放回從所述串表示它的對象的形式,然後是你可以把它變成一個cookie。

3

如果它提供有意義的序列化或JSON.stringify(),請使用對象自己的.toString()方法。但請注意,Cookie通常長度有限,無法保存大量數據。

+0

關於餅乾長度的注意事項 – 2018-03-09 00:47:29

2

一個cookie適配類來自: http://www.sitepoint.com/cookieless-javascript-session-variables/

所有你需要做的就是設置和獲取你需要存儲在cookie中的變量。

工作用:整數,字符串,陣列,列表Complex對象

例:

var toStore = Session.get('toStore'); 

if (toStore == undefined) 
    toStore = ['var','var','var','var']; 
else 
    console.log('Restored from cookies'+toStore); 

Session.set('toStore', toStore); 

類別:

// 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 = {}; } 
}; 
})();