如何从JavaScript的Cookie中检索Json数据?

时间:2018-12-27 17:54:14

标签: javascript json cookies

这是添加到Cookie的购物车,但是我不清楚这一点,而且当我单击“刷新”并添加tocart onclick函数时,所有cookie值都将被覆盖,

我的目标解决方案是 cookievalue = [{id:1,price:33,qty:1},{id:1,price:33,qty:1},{id:1,price:33,qty:1}];

var cartstring = {};         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=/";
});

非常感谢您的关注。

1 个答案:

答案 0 :(得分:0)

有关如何写入和读取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]));