创建一个 json cookie 数组

Creating a Json Cookie Array?

本文关键字:json cookie 数组 一个 创建      更新时间:2023-09-26

我正在尝试使用jquery的json创建一个cookie数组。这是到目前为止除了数组部分之外有效的脚本。有人可以告诉我如何做这样的数组......

    <script type="text/javascript">
       //The database value will go here...
       var cookievalue= {'tid1':'ticvalue1','thid1':'thidvalue1','tid2':'ticvalue2','thid2':'thidvalue2'};
       //Create a cookie and have it expire in 1 day.
       $.cookie('cookietest', cookievalue, { expires: 1 });
       //Write the value of the cookie...
       document.write($.cookie('cookietest'));
    </script>

我遇到的问题是当我将数组传递给它存储[object object]而不是数组值的 cookie 时。因此,如果我遍历数据,那么我将使用多个 cookie 而不是一个将数组值存储在

我遇到的问题是,当我将数组传递给 cookie 时,它存储的是 [对象对象] 而不是数组值。因此,如果我循环访问数据,那么我将使用多个 cookie 而不是一个存储数组值的 cookie。

现在你说白了!因此,我们可以在没有数千条评论的情况下为您提供帮助;)


    <!DOCTYPE html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="../js/jquery-1.7.2.js" type="text/javascript"></script>
    <script src="https://raw.github.com/douglascrockford/JSON-js/master/json2.js" type="text/javascript"></script>
    <script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js" type="text/javascript"></script>
    </head>
    <body>
        <script>
            $(function() {
                var cookieValueString = JSON.stringify( 
                    [
                        {
                            'column1':'row1col1',
                            'column2':'row1col2'
                        },
                        {
                            'column1':'row2col1',
                            'colum2':'row2col2'
                        }
                    ] 
                );
                $.cookie('cookietest', cookieValueString, { expires: 1 });
                var arrayFromCookie = JSON.parse($.cookie('cookietest'));
                for(var i = 0; i < arrayFromCookie.length; i++) {
                    alert("Row #" + i
                           + "- Column #1: " + arrayFromCookie[i].column1
                           + " - Column #2: " + arrayFromCookie[i].column2);
                }
            });
        </script>
    </body>
    </html>

您正在创建一个具有这些属性的对象。而且你使用的是单引号而不是双引号(据我所知,在 json 中你必须指定一个带双引号的字符串)。

试试:

      var cookievalue= [{"tid1":"ticvalue1"},{"thid1":"thidvalue1"},{"tid2":"ticvalue2"},{"thid2":"thidvalue2"}];

所以解析后你会得到以下内容: 结构

cookievalue[0].tid1 == "ticvalue1"<br/>
cookievalue[1].thid1 == "thidvalue1"<br/>
cookievalue[2].tid2 == "ticvalue2"<br/>
cookievalue[3].thid2 == "thidvalue2"<br/>