Section C. The response format


C. The response format

An XMLHttpRequest allows you to retrieve any sort of data format from the server. In practice, most Web developers restrict themselves to XML, HTML, JSON (JavaScript Object Notation), CSV (comma-separated values), or another form of plain text.

In this section we'll discuss the advantages and disadvantages of all of these formats. I'll use the return values of XMLHTTP Speed Meter as examples. The script expects XML, but it could easily be changed to accommodate JSON or CSV. HTML, as we'll see, is much harder to use in this specific case.

XML

Because of the name XMLHttpRequest, many developers select XML as their return format. There's nothing wrong with that, but you should bear in mind that other formats are possible, and that sometimes they're more useful.

The big advantages of XML are that most programmers know what it is, and that XML files can be read and used by a variety of programming languages. If you announce to other developers that you're going to use XML they'll nod sagely, while announcing any of the other formats may cause a few raised eyebrows and requests for further explanations. Socially, XML is the most acceptable format.

What about its technical advantages and disadvantages? The most obvious advantage is that you can use nearly all W3C DOM methods and properties on an XML fileyou don't have to learn any new programming tricks.

The disadvantage of XML is that both the server response and the script that interprets it can become quite verbose. You have to read out every interesting XML element separately, and you have to create every HTML element you need separately, too. This can make for quite lengthy scripts that become hard to read and maintain.

Example

Let's look at XMLHTTP Speed Meter's response:

<?xml version="1.0" encoding="utf-8"?> <wanadoo>  <distance>2495</distance>  <speed>15</speed>  <message/>  <error>0</error> </wanadoo> 


The <distance> and <error> elements are not used by my script. They might come in useful in other situations, and their presence does not hinder my script in any way, so I don't mind them being there.

If the postal code is incorrect, we get an error message like this:

<?xml version="1.0" encoding="utf-8"?> <wanadoo>  <distance>0</distance>  <speed>0</speed>  <error>1</error>  <message>Your postal code and/or house number are incorrect.</message> </wanadoo> 


We already saw the script that reads out the relevant data and does something with them:

[XMLHTTP Speed Meter, lines 52-59]

function catchData(req) {     var returnXML = req.responseXML;     if (!returnXML) return;     var speed = parseInt(returnXML. getElementsByTagName('speed')[0].firstChild.nodeValue);     if (speed != currentSpeed)            moveToNewSpeed(speed);     currentSpeed = speed;     var error = returnXML.getElementsByTagName('message')[0]. firstChild; 


Since we're only reading out two tags and don't generate any HTML, this is a pretty simple function. Be warned, however, that as soon as you start generating HTML, such a function becomes much, much more complicated.

HTML

In certain respects, HTML is the best choice for importing data to a Web site. The reason is, of course, that Web sites already work with HTML, and that adding extra bits of it is extremely simple:

function catchData(req) {     var newHTML = req.responseText;     document.getElementById('someID').innerHTML = newHTML; } 


You read out the responseText, i.e., the response as a text string. Since this text is already HTML, you can simply paste it into some element's innerHTML, and the page will contain the new data.

But if you want to read out bits of data and write them into several elements, or pass them on to other functions, as I do in XMLHTTP Speed Meter, HTML becomes hard to work with.

Showing error messages is easy; if the server-side script returns something like this, we just paste it in the appropriate HTML element:

<p>Your postal code and/or house number are incorrect.</p> 


HTML and Forms in Explorer

Explorer seems to be unable to add HTML snippets that contain a <form> tag to a page. It also refuses to cooperate when you want to load HTML snippets into a <form> element.


However, reading out the speed is another thing. The script does not want to print out the speed, but instead needs to send it on to another function that starts up the animation. In theory this is possible, but it's not really intuitive or easy:

// returned data 15 // script that does something: function catchData (req) {     var response = req.responseText;     var speed = parseInt(response);     if (speed != currentSpeed)            moveToNewSpeed(speed); } 


This method would work. The disadvantage is that the returned data is just "15", and that doesn't really count as HTML. Besides, it doesn't make use of HTML's main advantage: pasting the response into an element.

All in all, the HTML response format is not suited for XMLHTTP Speed Meter, or for any script that needs to manipulate the server data instead of just printing them on the screen. On the other hand, as we'll see in 10D, HTML is the most accessible format.

JSON

The JavaScript Object Notation format returns a string that should be interpreted as a JavaScript object. This string contains a JavaScript object literal (see 5J).

JSON Introduction

JSON was invented by Douglas Crockford. See http://www.json.org/ for an extended introduction to the format.


This would be the JSON equivalent of XMLHTTP Speed Meter's XML response:

{     distance: 2495,     speed: 15,     message: null,     error: 0; } 


Or, in case of an error:

{     distance: 0,     speed: 0,     message: "Your postal code and/or house number are incorrect.",     error: 1; } 


The advantage of JSON is that it's slightly more in line with JavaScript's internal structure than XML.

The disadvantage is that the syntax is very precise and unique to JavaScript, which means that developers without experience in JavaScript will not be able to create JSON strings on the fly. Besides, the script you need to create an HTML structure to hold the data is roughly as verbose as a script that reads out XML.

How do we interpret such a JSON string? For example, catchData() would become something like this:

function catchData(req) {     var responseObject = eval('(' + req.responseText + ')');     var speed = responseObject.speed;     if (speed != currentSpeed)             moveToNewSpeed(speed);     var error = responseObject.message;     // handle error } 


CSV

Note

CSV is the only plain-text format we'll cover here, but others are similar enough that this will serve as an adequate example.


Comma-separated values (or values separated by another character) is one of the oldest data-retrieval systems in use. It simply sends back a string, within which the commas denote where one bit of data ends and another one starts.

The advantages of CSV are that it's the shortest and most efficient data format, it has a venerable pedigree, and it's well-known by developers in all sorts of languages.

The disadvantage is that the file doesn't contain any clue about the interpretation of the data. Files in other formats contain some sort of pointer (be it an XML or HTML tag or a JavaScript property name) that tells you what sort of data they hold.

For instance, if I swap the speed and message tags (XML) or properties (JSON), the XML and JSON scripts would continue to function, since they access the speed and message data by tag or property name, not by their position in the response file. However, in a CSV file we can only access them by their position, and this requires client-side and server-side developers to be very disciplined in generating and reading the output.

These are CSV files for XMLHTTP Speed Meter:

2495,15,null,0 0,0,Your postal code and/or house number are incorrect.,1 


The data is read out and used in the following way:

function catchData(req) {     var data = req.responseText.split(',');     var speed = data[1];     if (speed != currentSpeed)           moveToNewSpeed(speed);     var error = data[2];     // handle error } 


As you see, the relevant data are being read by data[1] and data[2], so the function expects to find the speed at the second place, and the error message at the third. If a server-side programmer accidentally reversed the speed and message data, the JavaScript would not be able to extract the data it needs.

The best format?

It won't surprise you that there is no best formatonly formats that are best suited to a specific type of application or situation. In general, I decide on a response format in the following way:

  • If I want to add large chunks of data to a page, I opt for HTML, since it allows me to easily add data with only a few lines of script.

  • If the project is large and complicated and requires close cooperation with several programmers, I opt for XML, because this format is the most likely to be known and understood by all parties involved.

  • If I need to go through a lengthy response in search of the few bits of data I really need, I opt for either XML or JSON, since only these formats allow quick searches.

  • I never use CSV files, since I dislike the lack of metadata such as a speed or message tag or property name.

Of course you should feel free to disregard this advice and pick your own response format. Especially when you'll be doing both the client-side and the server-side coding, you should choose what comes naturally to you.



ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ppk on JavaScript. Modern, Accessible, Unobtrusive JavaScript Explained by Means of Eight Real-World Example Scripts2006
ISBN: N/A
EAN: N/A
Year: 2005
Pages: 116

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net