javascript - 如何从 javascript 中的 cookie 中检索 Json 数据?
问题描述
这是一个添加到购物车到 cookie,但我不清楚这个,当我点击刷新和 addtocart onclick 功能时,所有 cookie 值都将被覆盖,
我的目标解决方案是,cookievalue = [{id:1,price:33,qty:1},{id:1,price:33,qty:1},{id:1,price:33,qty:1}] ;
var 购物车字符串 = {}; var jsonstring = [];
var addtocart = (function(id,price,qty)
{
cartstring.id = id;
cartstring.price = price;
cartstring.qty = qty;
/* Also check here whether the cookie having data then the new value will be pushed and then inserted to cookie */
jsonstring = JSON.stringify(cartstring);
var d = new Date();
d.setTime(d.getTime() + (3600 * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = "cartObj=" + jsonstring + ";" + expires + ";path=/";
});
非常感谢您的关注先生/妈妈。
解决方案
如何写入和读取 json 数据的快速示例
const data = {
int: 22,
obj: { name: 'bar' },
arr: [0,1,2,3,4,5]
}
// write cookie
document.cookie = `json=${JSON.stringify(data)}`;
// read all cookie values
console.log(document.cookie)
// read json string value from cookie
console.log(document.cookie.split('json=')[1].split(';')[0]);
// parse json string value to object
console.log(JSON.parse(document.cookie.split('json=')[1].split(';')[0]));
推荐阅读
- javascript - Firebase 实时数据库 - 如何构建初始负载和侦听器
- angular - 如何在角度7中过滤数组的数组
- jenkins - 从 Jenkins 执行 denodo 任务
- matplotlib - 线性回归图解释
- python - 如何根据用户输入的日期获取第二天的日期?
- python-3.x - 一张图比较四张图
- powershell - 在过滤路径中搜索特定文件夹名称
- c++ - 如果 uint8_t 值乘以 uint8_t 是什么类型
- python - 如何根据逗号拆分包含多个字符串值的csv行,但不考虑大括号{}内的逗号
- amazon-web-services - 在页面重新加载 ionic 4 应用程序不允许键入任何输入