2009-12-12 43 views
0

是否可以放入一個Javascript對象數組並再次檢索它?有沒有簡單的方法?在將它們存儲在cookie中之前,是否必須序列化爲字符串?如何把一個JavaScript對象的數組放入cookie中?

接下來的代碼顯示了我想要達到的目標:提前

writeCookie("items",[new Item(3,15.00,2,"GR-10 Senderos"),new Item(4,45,1,"GR-10 Senderos<br/>GR 88 Senderos del Jarama<br/>Camino del Cid")],5*365); 
$(document).ready(function() { 
    var items = readCookie("items"); 
}); 

function writeCookie(name, value, days) { 
    // By default, there is no expiration so the cookie is temporary 
    var expires = ""; 

    // Specifying a number of days makes the cookie persistent 
    if (days) { 
    var date = new Date(); 
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); 
    expires = "; expires=" + date.toGMTString(); 
    } 

    // Set the cookie to the name, value, and expiration date 
    document.cookie = name + "=" + value + expires + "; path=/"; 
} 

function readCookie(name) { 
    // Find the specified cookie and return its value 
    var searchName = name + "="; 
    var cookies = document.cookie.split(';'); 
    for(var i=0; i < cookies.length; i++) { 
    var c = cookies[i]; 
    while (c.charAt(0) == ' ') 
     c = c.substring(1, c.length); 
    if (c.indexOf(searchName) == 0) 
     return c.substring(searchName.length, c.length); 
    } 
    return null; 
} 

function eraseCookie(name) { 
    // Erase the specified cookie 
    writeCookie(name, "", -1); 
} 

謝謝!

+0

請記住,cookie具有大小限制(IE的限制性較強的瀏覽器,每個cookie最多允許4,096字節http://is.gd/5kvH7),並且不要忘記cookie將以*每個*請求,這就是爲什麼建議爲圖像和組件提供無cookie的域。 http://is.gd/5kwcx – CMS 2009-12-12 05:03:26

+0

我想存儲購物車項目,一些文本和數量。我認爲大小不會是一個問題。不過,謝謝你提供的信息。不勝感激! – 2009-12-13 23:54:07

回答

3

我會JSON將它編碼爲一個字符串,然後將其存儲在cookie中。

0

你好,你必須序列化它作爲一個字符串。 Garsh!請記住,Cookie只是通過網絡發送的HTTP標頭,只是字節數組。但不只是任何字節。 HTTP頭幾乎遵循只允許普通7位ASCII的MIME規範。所以序列化,就像馬呂斯說的那樣。使用json.org/json2.js。或者用String.join滾動你自己的序列化。

相關問題