[英]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.