我正在尝试使用 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/