AJAX - The Complete Reference

(avery) #1

148 Part I: Core Ideas


CSV
In the previous section, you saw that a very simple text format such as a comma-separated
value (CSV) format is a terse but still effective way to transmit request data. The same holds
for response data. Preparation on the server side isn’t terribly difficult, but you will have to
manually assemble the data yourself and make sure to correctly indicate the Content-Type
header as text/plain.

header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: text/plain");
$message = "$rating,$average,$votes";

The network trace shows the terse CSV response:

Now when you receive the data, you have some work to do in splitting the response
into its logical values. Here we rely on a priori knowledge of the meaning of each value at
each particular position in the comma-separated list as:

/* decode response */
var results = xhr.responseText.split(',');
var rating = results[0];
var average = results[1];
var total = results[2];

Once the data is decoded, you then add the response string to the document the same
as before:

/* add to page */
var responseOutput = document.getElementById("responseOutput");
responseOutput.innerHTML = "Thank you for voting. You rated this a
<strong>" + rating + "</strong>. There are <strong>" + total + "</strong>
total votes. The average is <strong>" + average + "</strong>. You can see
the ratings in the <a href='http://ajaxref.com/ch4/ratings.txt' target=
'_blank'>ratings file</a>.

We must point out that we have been quite careful to set the MIME types of responses
correctly to indicate the type of content sent such as text/plain. In practice, some Ajax
developers leave the response value the default text/html and infer the content type
Free download pdf