javascript - 创建一个 Json Cookie 数组?

标签 javascript jquery json

我正在尝试使用 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,并将数组值存储在

最佳答案

the problem I'm having is when I pass the array to the cookie it is storing [object object] instead of the array values. So if I loop through the data then I will multiple cookies instead of one cookie with the array value stored in.

现在你说得很清楚了!这样我们就可以在没有成千上万条评论的情况下为您提供帮助;)


    <!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>

关于javascript - 创建一个 Json Cookie 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11930994/

相关文章:

javascript - 无法在 d3.js 中的同一页面上生成两个饼图

javascript - 如何将 onmousedown 事件绘制为存储在数组某个索引处的值,而不是整个数组调用?

javascript - JavaScript 和 Python 之间的交互

javascript - PHP、Jquery、JS。 2个按钮在彼此身上,如何通过1次鼠标点击来点击它们?

javascript - 是否有访问 JSON.parse XMLHTTPRequest.responseText 的通用方法?

jquery - 使用带有格式化表格数据的 jsPDF 创建 pdf

Javascript 动态分组

jquery - jQuery Datatables 分页中如何返回特定页面?

json - 如何使用 mustache 呈现 JSON 模板

javascript - 解析一些 JSON