[英]How to retrive Json data from cookie in javascript?
这是添加到 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]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.