AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 149


PART I


themselves or add some other header to indicate it. It is true there are browser MIME type
concerns, in particular with Internet Explorer guessing content types. However, within the
context of XHRs and the responseText property, this doesn’t seem to be a problem and is
more a case of sloppiness or distrust rather than a known problem.

YAML
The YAML format takes a bit more preparation than the previous examples, and you most
likely must rely on a server-side library to prepare the data for transmission as shown by a
simple PHP fragment:

header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: text/x-yaml");
require_once('spyc.php');
$yamlResponse = new ResponseData();
$yamlResponse->rating = $rating;
$yamlResponse->votes = $votes;
$yamlResponse->average = $average;
$message = Spyc::YAMLDump($yamlResponse);
echo $message;

The data transmission here reminds you how terse YAML is, but you’ll find that
handling the content on the client side can be a chore.

As with CSV responses, you will need to decode the YAML response before it can be
used. Unfortunately as of the time of the writing of this book, no general JavaScript YAML
decode library is available. Given that you know that the format of the response is a simple
list of names and values in YAML delimited by colons, however, it should be easy enough
to split them apart yourself:

var responseArray = new Array();
var yaml = xhr.responseText.split("\n");
for(i=1; i < yaml.length - 1; i++)
{
var nameValue = yaml[i].split(":");
responseArray[nameValue[0]] = nameValue[1];
}
Free download pdf