简体   繁体   中英

Javascript - set/get cookie - array

I am trying to set/get an array as a cookie in Javascript as follows:

    let features = [];
    
    for(const property in object) {
        ...
        let feature = new Feature(...);

        features.push(feature);
    }

    cookie.set('features', JSON.stringify(features));
    
    console.log(JSON.parse(cookie.get('features')));

and I get the following error: VM21081:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0

PS If I do not use stringify/parse the result is undefined.

Could you help me, please?

Thank you in advance.

the issue is that you try to set and get cookies in the browser on the local environment. I copied from the answer in this topic ( Why does Chrome ignore local jQuery cookies? )

'Chrome doesn't support cookies for local files (or, like Peter Lyons mentioned, localhost*) unless you start it with the --enable-file-cookies flag. You can read a discussion about it at http://code.google.com/p/chromium/issues/detail?id=535 .

*Chrome does support cookies if you use the local IP address (127.0.0.1) directly. so in the localhost case, that could be an easier workaround.'

to test your code you can use w3school editor, here is an example: https://www.w3schools.com/code/tryit.asp?filename=GHTVNK8POVWM

(click run button to see the result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM