AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 129


PART I


A few examples showing usage are given next:

var payload = "";
payload = serializeForm(contactForm);
payload += serializeObject({name: "Angus",breed: "Scotty",age: 5});

This serialization works only for the standard data encoding form x-www-form-urlencoded
and will get a bit more complicated as soon as other encoding formats are supported. Let’s
look at the other possibilities first and revisit the method again later.

Using Other Input Formats


It is certainly possible to use other formats for sending data to a server. However, using
another format will likely take more work to prepare for sending on the client side and
for decoding on the server side. We present numerous possible choices for transmission
influenced by what is commonly used as a response format. Before starting, we make what
we hope is an obvious point. The choice of data format within your own application is
limited solely by your imagination; thus, you are certainly not restricted to the types
discussed here.

XML


Given the emphasis on XML in the Ajax acronym, you might wonder why the XML format
isn’t used much for transmission of data rather than just responses where it is typically found.
The reason that it is not often considered is most likely due to the difficulty of encoding and
decoding a request in such a format. For example, consider the ever-faithful rating example
implemented to send XML instead of standard x-www-form-urlencoded formatted data. In
this example, form values are read and escaped as normal before transmission.

/* read form values and encode their data */
ratingVal = encodeValue(ratingVal);
comment = encodeValue(comment);

However, now instead of forming name-value pairs, an XML packet containing similar
data is formed.

/* form XML packet */
var payload = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n";
payload += "<vote>\r\n";
payload += "<rating>" + ratingVal + "</rating>\r\n";
payload += "<comment>" + comment + "</comment>\r\n";
payload += "</vote>\r\n";

After creating the data packet, the XHR is created as normal, but in this situation, the
Content-Type header is set to indicate that the data is in XML format.

var xhr = createXHR();
if (xhr)
{
xhr.open("POST",url,true);
Free download pdf