Javascript -在JSON对象中设置多个cookie

gmxoilav  于 2022-12-10  发布在  Java
关注(0)|答案(2)|浏览(150)

场景是在网站上,用户可以多次选择商店,我想获取用户选择的所有商店,我想使用cookie来实现这一点。
我想将Cookie保存为JSON,例如{“storeId”,“0010”}、{“storeId”,“0011”}等。

**因此下面的代码:**它不是追加cookie,只是覆盖值

function setCookieJson(name, value) {
    var cookie = [name, '=', JSON.stringify(value), '; domain=.', 
    window.location.host.toString(), '; path=/;'].join('');
    document.cookie = cookie;
} 

setCookieJson('storeId', storeId);

从以上代码中得到的结果是:

存储ID =“0010”
如果换了商店
存储ID =“0011”

但是,预期结果应为{“存储ID”,“0010”},{“存储ID”,“0011”}

lfapxunr

lfapxunr1#

我已经通过实现cookie已经存在检查解决了这个问题:

代码:

function setCookieJson(name, value) {
    var cookieExisted = getCookie(name).replace(/"/g,"");
    var cookie;
    if (cookieExisted.length) {
        if (!cookieExisted.includes(value)) {
            cookie = [name, '=', JSON.stringify(value + ',' + cookieExisted), '; domain=.', window.location.host.toString(), '; path=/;'].join('');
        }
    } else {
        cookie = [name, '=', JSON.stringify(value), '; domain=.', window.location.host.toString(), '; path=/;'].join('');
    }
    document.cookie = cookie;
}
muk1a3rh

muk1a3rh2#

.netflix.com TRUE / FALSE 1695211041 NetflixId v%3D2%26ct%3DBQAOAAEBELLnIZckwn7Gw1HwZkhy9sWB0FvwNezIEbeInbq7xvxIdsUiAjYgCSttbOJABTc6FezxdbP5De2jPFbQVonyJkwLD2HFIQ7-sKNkWdgDkOYYvSeNXhfu232mFeEes8xB_ItWHH5H8wHwOOtPIM3dnABTGSDiHggD428Sa0WhLrYsH6Fh_ZvRIn-pt7u0gQlRamfEYZtksk9tvi2q6oBsRQS5gtWBwahy4ae7jdh0RvUQECpdBYLMXE7BYuqULaShhFojg8Xs9xCjaM5fOP852TQ_tpWyfqB0_dZfh4MKCZqWpNPiDg9OJS10iOZXjopmHDDckjFxBMNld4d-xvQsfYVprQHKQ6HWf0se3_gElxXrOA0jRjTuDv8bhUtpY3icW274Cez2-gQ54k_IWtDKV2qQC5wsyFaNahS3gIfX5TlwRAUXF7UoP4O4H_9efaQmEhkRU-RU8sT5yn0B8OFXfwe9KsNSkrXpZ_FsgRKAL5QdxlRCgJP5kiu1i75v1NmNjUtgza655Q0ix3vuPcdDkRHYW1lyjUEA6ZVoRihUeqYXm5olkiqzWCqlEqMp8EsyvLb5GrCPr4nImTMTAafg7k4I18ChO4uow4VQJO2oHarA-IHCN80_CTcOrXgpg3Pb3o%26bt%3Ddbl%26ch%3DAQEAEAABABTlBXonnS9xcrNPvKjEbYQsgSCWSTvWmD0.%26mac%3DAQEAEAABABS3Zp0Z7zcrvqcdtHA2PNWt6eM1banGCbk. .netflix.com TRUE / FALSE 1695211043 OptanonConsent isIABGlobal=false&datestamp=Tue+Sep+20+2022+14%3A57%3A23+GMT%2B0300+(GMT%2B03%3A00)&version=6.6.0&consentId=8506c850-657e-4f77-aca8-9d2fde6f5add&interactionCount=1&landingPath=NotLandingPage&groups=C0001%3A1%2CC0002%3A1%2CC0003%3A1&hosts=H12%3A1%2CH13%3A1%2CH51%3A1%2CH45%3A1%2CH46%3A1%2CH52%3A1%2CH48%3A1%2CH49%3A1&AwaitingReconsent=false .netflix.com TRUE / FALSE 1695211041 SecureNetflixId v%3D2%26mac%3DAQEAEQABABSlIpz1PleUW0Oon1j3DATDRpax5VG3k5E.%26dt%3D1663675045989 .netflix.com TRUE / FALSE 1663685841 flwssn 44dbe084-39d7-485d-8306-987d8b719420 .netflix.com TRUE / FALSE 1695211041 nfvdid BQFmAAEBEHC2pA81o3BnMcGbdUheOxVgqM4KfTxcxsx-RZGxWS_Qlxv7EhTteflvRx70z8ggOZ9OhvZvn1ixtRDXquHq7UJbFPGNJvzXfdgoC34Sgzn_mBaEeTmnmqumbGWbiPuIri-i-b_R2plQFsL9T2jCyY6P .netflix.com TRUE / FALSE 1695220424 memclid 0f9e8ade-d9e9-4fae-bb69-a99b9c08df70 .netflix.com TRUE / FALSE 1663686211 profilesNewSession 0

相关问题