简体   繁体   中英

One cookie containing all data using JavaScript

I need to set a lot of key->value pairs inside a cookie. What I am doing as of now is saving each data point as a separate cookie which is easy but not the best optimal solution. What I would rather love to do is to have just one cookie, with all the values saved in it as a key->value pair.

I am looking for a library / wrapper which can handle create cookie / read cookie / delete cookie functions, where the actual job would be to read the master cookie, parse it, find the appropriate key value and use it.

Is there soemthing like this already present.? If not, what is the best way to do it.. I dont want to include JSON library to serialize my cookie, any other recommendation.

Thanks Sparsh

I don't think there is any 'library' to manage cookies as it's quite simple.

According to w3school ( http://www.w3schools.com/js/js_cookies.asp ), you can read cookies by :

function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
    }
}

Create cookie / read cookie / delete cookie is just the manipulation of the cookie string. And update your cookie to internet navigator:

document.cookie=your_cookie_string

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