Remember the limitations for a cookie-driven site: Only 20 cookies per domain are allowed. Also, if users get a warning when a cookie arrives, the more cookies you send the more annoyed your users will be. Therefore, it can be a clever idea to store more than one bit of information in a cookie. For this to work, the cookie data must be serialized. There are several different approaches to this, including some really advanced ones. However, if you just want to store a list of name/value pairs, URL encoding is the easiest thing to implement: Serializing an Object (serialize.html; excerpt)
When complex data is used in a cookie, code in the following fashion may be used: document.cookie = "data=" + serialize(myComplexData) The way back requires a bit more code, but consists largely of splitting the data into individual pairs and extracting names and values out of the result: Unserializing an Object (serialize.html; excerpt)
The code file serialize.html serializes and unserializes an object, without using cookies to make the code a bit shorter. Note At http://www.iconico.com/workshop/jsSerializer/, a more complex serializer is shown that converts an object into XML. Also, the discussion on JSON from Chapter 11, "AJAX (and Related Topics)," may be of interest here. |