首页 > 解决方案 > 如何从 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=/";
});

非常感谢您的关注先生/妈妈。

标签: javascriptjsoncookies

解决方案


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

推荐阅读