JavaScript Phrasebook

for (var el in data) { namevalue += "&" + escape(el) + "=" + escape(data[el]); }

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)

function serialize(data) { var namevalue = ""; for (var el in data) { namevalue += "&" + escape(el) + "=" + escape(data[el]); } return namevalue.substring(1); }

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)

function unserialize(data) { var object = new Array(); var pairs = data.split(/&/g); for (var i=0; i<pairs.length; i++) { if (pairs[i].indexOf("=") > -1) { object[unescape(pairs[i].substring( 0, pairs[i].indexOf("=")))] = unescape(pairs[i].substring( pairs[i].indexOf("=") + 1)); } } return object; }

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.

Категории