[英]how could I can I read an array I save in a cookie with jquery.cookie?
I am using jquery.cookie ( https://github.com/carhartl/jquery-cookie/tree/v1.4.1 ) and Ive been having many problems with this, I am trying to save an array of this structure 我正在使用jquery.cookie( https://github.com/carhartl/jquery-cookie/tree/v1.4.1 )并且我遇到了很多问题,我正在尝试保存此结构的数组
var obj = {
'row1' : {
'key1' : 'input1',
'key2' : 'inpu2'
},
'row2' : {
'key3' : 'input3',
'key4' : 'input4'
}
};
But when I want to read it I get this 但是当我想读它的时候
row1%5Bkey1%5D=input1&row1%5Bkey2%5D=inpu2&row2%5Bkey3%5D=input3&row2%5Bkey4%5D=input4
I am sending it at this way: 我以这种方式发送:
$.cookie('listresult', $.param(obj), { expires: 10 });
The worst is that sometimes works, and sometimes doesnt, so, I have no idea whats wrong... Any idea how to send and transform the data? 最糟糕的是,有时可行,有时却没有,所以,我不知道出了什么问题……知道如何发送和转换数据吗?
To read it I use this 要阅读它,我用这个
var cookieValue = $.cookie("listresult");
When I try this... doesnt work 当我尝试这个...不起作用
$.parseJSON($.cookie("listresult");)
Thanks 谢谢
You shouldn't use jquery.param
method. 您不应该使用
jquery.param
方法。 It is intended for use with HTTP (AJAX) requests so that's not your case. 它旨在与HTTP(AJAX)请求一起使用,因此情况并非如此。 You have to use
JSON.stringify
on writing cookie and JSON.parse
on reading: 您必须在编写Cookie时使用
JSON.stringify
,在阅读时必须使用JSON.parse
:
// write (save):
$.cookie('listresult', JSON.stringify(obj), { expires: 10 });
// read (restore):
var obj = JSON.parse($.cookie('listresult'));
If you carefully read jQuery plugin's manual, you'll find this: 如果您仔细阅读jQuery插件手册,将会发现:
json
JSON
Turn on automatic storage of JSON objects passed as the cookie value.
打开作为cookie值传递的JSON对象的自动存储。 Assumes JSON.stringify and JSON.parse:
假设JSON.stringify和JSON.parse:
$.cookie.json = true;
$ .cookie.json = true;
This way your JavaScript objects will be serialized to JSON when you set the whole cookie, and they'll get deserialized into a JavaScript again when you retrieve that cookie. 这样,当您设置整个cookie时,您的JavaScript对象将被序列化为JSON,而当您检索该cookie时,它们将再次被反序列化为JavaScript。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.