javascript - 如何将 javascript 对象数组放入 cookie 中?

标签 javascript

是否可以放入 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/

相关文章:

javascript - 如何向 watson 对话响应添加操作?

javascript - Angular 中 $scope.Variable 和 $scope.Function 之间的区别?

javascript - 与经过验证的位置进行交互? - 谷歌地图

c# - "The Type or namespace ' AjaxControlToolkit' 无法找到...”的解决方案是什么?

javascript - 如何通过单击谷歌地图内的按钮来调用 Vue js 的方法

JavaScript 类

当我使用 document.execCommand ("copy"时,javascript 换行符不适用)

javascript - Grails + Google map API

javascript - 从 react 中的组件中确定无状态组件名称

javascript - 未处理的异常:System.TimeoutException:请求 channel 在00:01:59.4579323之后等待答复时超时