如何在cookie中放置一个javascript对象数组?

时间:2009-12-12 01:51:04

标签: javascript

是否可以放置一个Javascript对象数组并再次检索它?有一个简单的方法吗?在将它们存储在cookie中之前,是否必须将其序列化为String?

下一个代码显示了我想要实现的目标:

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);
}   

提前致谢!

2 个答案:

答案 0 :(得分:3)

我会将JSON编码为字符串,然后将其存储在cookie中。

答案 1 :(得分:0)

哎呀,你必须将它序列化为一个字符串。 Garsh!请记住,cookie只是HTTP头,它通过网络发送,只是字节数组。但不只是任何字节。 HTTP标头几乎遵循MIME规范,只允许普通的7位ASCII。所以序列化它,就像马吕斯所说的那样。使用json.org/json2.js。或者使用String.join滚动自己的序列化。