I'm using the jquery cookie plugin to store an object in a cookie. The object contains various properties which store information about the visitor to the site. Is there a way to retrieve the cookie and access these properties? Or do I have to store each piece of data in a separate cookie? Here's my code:
c.consumerID = data.LoginConsumer.ConsumerId;
c.surveyCount = data.LoginConsumer.SurveyCnt;
c.vehicleCount = data.LoginConsumer.Veh开发者_如何学JAVAicleCnt;
c.sid = data.LoginConsumer.SurveyId;
c.aid = data.LoginConsumer.ActivityId;
c.loggedIn = true;
$j.cookie('consumerCookie', c, { path: '/' });
console.log($j.cookie()); //WANT TO RETRIEVE THE VALUES OF THE OBJECT IN THE COOKIE HERE, LIKE c.sid
Cookies store strings, so if you want to store six properties from an object, you will either have to store each property individually as it's own string and give each a name or you will need to combine all the property values into one string.
You could use a JSON library to stringify the whole object and then read the JSON back in when reading the cookie. For example to store all the data in the cookie, it would work like this:
$j.cookie('consumerCookie', JSON.stringify(c), { path: '/' });
And, to read it back in, you could do this:
var c = $j.parseJSON($j.cookie('consumerCookie'));
Note: it doesn't appear that jQuery has stringify built-in so if you go the stringify route, for older browsers you will have to make sure that there is a JSON.stringify capability.
You can store it all in one cookie, but you'll need to serialize the object somehow, perhaps JSON. If you go the JSON route, just use the json2.js library.
Also, remember there is a limit on individual cookie size. 4k in most browsers.
Depending on what you're doing, and if you're also using PHP, you may want to instead use PHP sessions and store everything in an attribute of the $_SESSION variable. This can be retrieved with a simple AJAX call using JSON.
精彩评论