AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 135


PART I


As seen in the previous, more complex JSON examples, white space can be used
liberally and will add in readability if you expect human inspection.
To see JSON in use, the simple rating example will be modified to transmit JSON
instead. To accomplish this task, we use the JavaScript library for JSON at http://www.json.org/
js.html. This library provides a number of useful features, including a “stringifer” that takes
a JavaScript object and converts it to JSON format. To accomplish this, the library adds a
toJSONString()method to the generic JavaScript Object using a prototype so that the
object can be serialized or, if you like, “stringified” for transmission.

var payloadJson = new Object();
payloadJson.rating = escapeValue(ratingVal);
payloadJson.comment = escapeValue(comment);
var payload = payloadJson.toJSONString();

Once the payload is created, it is sent appropriately, making sure to stamp the payload
with the appropriate Content-Type header:

xhr.setRequestHeader("Content-Type", "application/json");

A capture of the network transmission of JSON is shown here:

On the server side, as with XML, the transmitted JSON data must be decoded. There are
numerous libraries available at json.org that make this task quite easy. The following small
snippet of PHP code handles the JSON transmission.

$payloadString = $GLOBALS['HTTP_RAW_POST_DATA'];
if (strstr($headers["Content-Type"], "application/json"))
{
require_once('JSON.php');
Free download pdf