AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 123


PART I


because the associated character such as left and right brackets and the comma ( [ , ] ) are
safely found in URLs. For example, given a JavaScript array like so:

var pets = ['Angus Powell', 'Rufus', 'Tucker O\' Reilly'];

to be sent to a server program handle.php, you might form a URL like:

http://ajaxref.com/pet-tracker.php?pets[]=Angus+Powell&pets[]=Rufus&pets=[]
Tucker+O%27Reilly

Now, you might wonder how to encode a JavaScript object value like the following into
the URL format:

var dog = {name: "Angus",
breed: "Scotty",
age: 5}

In JavaScript, objects and arrays are pretty much interchangeable, so the previous object can
be alternatively written as an associative array like so:

dog[name] = "Angus Powell";
dog["breed"] = "Scotty";
dog["age"] = 5;

Given that form, it can be encoded into a standard x-www-form-urlencoded payload
like so:

http://ajaxref.com/pet-tracker.php?dog[name]=Angus+Powell&dog[breed]=Scotty
&dog[age]=5

We present a basic encodeObject() function here that will encode a passed array or
object into a URL safe form. It relies on the previously defined encodeValue() function to
perform the correct value encoding.

function encodeObject(obj, indexString)
{
var queryString = "";
if(typeof(obj) == "object")
{
for(keyStr in obj)
{
var key = keyStr;
var val = obj[key];
if (indexString)
{
if (!obj.length)
key = indexString + "[" + encodeValue(key) + "]";
else
key = indexString + "[]";
}
if (typeof(val) == "object")
queryString += encodeObject(val, key);
Free download pdf