tol*_*anz 4 javascript cookies json
我有一个简单的数组,我正在尝试JSON编码并设置为cookie.我使用json2.js脚本编码为JSON.我使用以下代码来设置cookie:
jQuery(document).ready(function(){
var ids = ['1', '2'];
JSON.stringify(ids);
setCookie(cookieName, ids, 1);
});
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
Run Code Online (Sandbox Code Playgroud)
将数组转换为JSON并将其记录在控制台中后,我得到:
["1", "2"]
Run Code Online (Sandbox Code Playgroud)
这是我所期待的.然后我用以下函数读出cookie
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
当我读出cookie并将其记录在控制台中时,我得到:
1,2
Run Code Online (Sandbox Code Playgroud)
建议它是一个字符串,不再是JSON编码对象.我希望能够将cookie设置为JSON编码对象,将其读出并解析JSON对象,最后对数据执行操作.因此,我的问题是,如何将这样的JSON编码对象发送到cookie,以便在我读出它时将其解析为JSON?
一如既往地谢谢!
改变这个:
JSON.stringify(ids);
setCookie(cookieName, ids, 1);
Run Code Online (Sandbox Code Playgroud)
对此:
var str = JSON.stringify(ids);
setCookie(cookieName, str, 1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7107 次 |
| 最近记录: |