更新cookie中的数组

jQuery: update array in cookie

本文关键字:数组 cookie 更新      更新时间:2023-09-26

array -多维数组:

array[0] = [["1","2","3"],["1","2","3"],["1","2","3"]];

我需要将这个数组放入cookie ($.cookie('myCookie', JSON.stringify(array)))

现在是有趣的部分:

我需要维护myCookie并将新数据放入其中。

如果新生成的array有任何新的数据(元素),我需要从数组中提取新的元素并将它们添加到myCookie

最优雅的方式是什么?

最优雅的方法是按照您最初设置它的方式来做——用新的数组值覆盖您的cookie…

步骤如下:

  1. 创建一个JSON版本的数组jsonArray
  2. 以JSON格式下拉cookie
  3. 不反序列化,与jsonArray比较。
  4. 如果字符串不相同,则设置cookie为jsonArray

哦,我不知道用客户端语言在客户端存储上使用cookie。这是为了让php处理。

你应该看看localStorage,这样更方便。

localStorage['item'] = "Hello world";
alert(localStorage['item']); // Hello World
localStorage['item'] += "!!!";
alert(localStorage['item']); // Hello World!!!
localStorage['item'] = "Good bye";
alert(localStorage['item']); // good bye
var obj = {0:{text:"Hello"}, 1:{text:"World"}};
localStorage['item'] = JSON.stringify(obj);
JSON.parse(localStorage['item']); // {0:{text:"Hello"}, 1:{text:"World"}}

sessionStorage类似于localStorage,但只会持续到浏览器或选项卡关闭。


希望有帮助!

试试这样:

jQuery(document).ready(function($){
    var a=[];
a[0]= [["1","2","3"],["1","2","3"],["1","2","3"]];
a[1]= [["8","9","9"],["5","6","7"]];
var json_string_old=JSON.stringify(a); 
    //set myCookie
    $.cookie('myCookie',json_string_old); 
    //change the value of the array as per your requirments
   a[1]=[["2","2","2"],["2","2","2"]];
   a[2]=[["4","4","4"],["4","4","4"]];
    //convert it again to JSON String
var json_string_new=JSON.stringify(a);
    //now compafre & update accordingly
    if(json_string_new === json_string_old){
        console.log("same no need to update cookie");
    }else{
        console.log("different ok lets update the cookie");
       $.cookie('myCookie',json_string_new);     
    }    

});