AJAX - The Complete Reference

(avery) #1

PART II


Chapter 5: Developing an Ajax Library 189


Data Format Handling

As discussed in Chapter 4, there are many ways to send data. Request data is almost always
sent in x-www-form-urlencoded format, whether it is in a query string or a message body.
However, it doesn’t have to be. Putting data into XML, JSON, comma-separated plain text,
or any other format you might conceive of, is certainly possible. It is possible to even further
encode data, for example, using a base64 encoding. There are two functions provided in the
data object to address the serialization of data. First, the serializeForm() function can be
called on a form object directly.

AjaxTCR.data.serializeForm(form [,encoding,trigger,evt])

By default, this function will encode the form data in the standard x-www-form-
urlencoded format and return it as a string. However, if you pass it an encoding string
with a value of “application/json”, “text/plain”, or “text/xml”, it will return the
data in the corresponding format. For example, given the form below:

<form action="#" method="GET" name="form1" id="form1">
<input type="text" name="field1" value="Testing" />
<input type="radio" name="field2" value="On" checked="checked" />
<input type="radio" name="field2" value="Off" />
<input type="submit" value="send" />
</form>

the standard serialization returned by serializeForm()would be:

field1=Testing&field2=On

If you serialized the form into JSON you would get:

{"field1" : "Testing" , "field2" : "On" }

As XML, it would look like:

<?xml version="1.0" encoding="UTF-8" ?>
<payload>
<field1>Testing</field1>
<field2>On</field2>
</payload>

Finally, as plain text it would put the data into a comma-separated value form, like so:

field1=Testing,field2=On

When building a payload manually, the, second function, serializeObject(), is quite
useful.

AjaxTCR.data.serializeObject(payload,obj,encoding)

This function is passed a payload string (or blank if nothing is there yet), an object
containing values to add to the payload, and finally, one of the encoding string values used
in the previous example. It will then return a string containing the payload encoded in the
correct format. The library also includes functions to handle encode/decode data as base64,
Free download pdf