是否可以放入 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);
}
提前致谢!
最佳答案
我会将其 JSON 编码为字符串,然后将其存储在 cookie 中。
关于javascript - 如何将 javascript 对象数组放入 cookie 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1891944/