How to put an array of javascript object in a cookie?

Is it possible to put an array of Javascript objects and retrieve it again? Is there an easy way? Do I have to serialize as a String before storing them in a cookie? The next code shows what I want to achieve: writeCookie("items",[new Item(3,15.00,2,"GR-10 Senderos"),new Item(4,45,1,"GR-10 Senderos
GR 88 Senderos del Jarama
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); } Thanks in advance!
Keep in mind that cookies have size limits (the more restrictive browser it's IE, allows a maximum of 4,096 bytes per cookie is.gd/5kvH7), and don't forget that cookies will be sent with every request, that's why is recommended to have cookie-free domains for images and components. is.gd/5kwcx

以上就是How to put an array of javascript object in a cookie?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏