简体   繁体   English

在Cookie中保存数组并恢复Javascript

[英]Saving Array in Cookie and Restoring Javascript

I am trying to save an array and restore it on another page using Cookies. 我正在尝试保存一个数组,并使用Cookies将其还原到另一个页面上。

This is my code on Page 1: 这是我在第1页上的代码:

 var films = []; SetCookie("cart", films); 

Values are put into films through button on a cart, it stores values eg "Star Wars","Resident Evil". 通过购物车上的按钮将值放入电影中,它可以存储“星球大战”,“生化危机”等值。

On alert it is stored: Star Wars, Resident Evil 处于警报状态时将其存储:星球大战,生化危机

This is my code on Page 2: 这是我在第2页上的代码:

 function getMovie2() { var movie = []; movie = (GetCookie("cart")); var r = movie.length; alert(r); $("#table1").empty(); for (var i = 0; i < r; i += 1) { $("#table1").append("<tr><td>" + movie[i] + "</td><td>"); } } 

The lenght that I get from this is for EACH Character and not the number of things in Array. 我从中得到的长度是针对每个字符,而不是数组中的事物数量。

Where am I going wrong? 我要去哪里错了? I am trying to store an Array in a Cookie and then retrive it and save it in an Array. 我正在尝试将数组存储在Cookie中,然后检索它并将其保存在数组中。

Cookies can stores only string. Cookies只能存储字符串。 You need to make a JSON of the array and assign the jsoned string to the cookie 您需要制作数组的JSON并将jsoned字符串分配给cookie

You probably want to do something like: 您可能想要执行以下操作:

localStorage.stuff = JSON.stringify(['a', 'b', 2]);
console.log(JSON.parse(localStorage.stuff));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM