Chapter 4: Data Formats 151
PART I
And consumption is simply a matter of evaluating the responseText as code (http://
ajaxref.com/ch4/javascriptresponse.html).
eval(xhr.responseText);
If it seems a bit disconcerting to execute code sent over the wire, you are justified in
your sentiment. If you are sending JavaScript back that can be executed, anyone who calls
your script can execute the JavaScript, and there is indeed mischief to be performed here.
The eval() function is more than a bit dangerous and it turns out that you can use the
JavaScript-like format JSON much more safely. Also, as mentioned in Chapter 2, passing
script around is probably better performed using the <script> tag. As you will see in later
chapters, this affords you some interesting possibilities consuming Web services directly
from JavaScript.
JSON
To avoid some of the potential security problems of passing JavaScript, we opt instead to
send simple structures and values in JSON format. On the server side, there’s a bit of work
ahead to prepare the data for transmission, and you should likely be precise and use
a JSON specific Content-Type header:
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: application/json");
require_once('JSON.php');
$json = new Services_JSON();
$jsonResponse = new ResponseData();
$jsonResponse->rating = $rating;
$jsonResponse->votes = $votes;
$jsonResponse->average = $average;
$message = $json->encode($jsonResponse);
echo $message;
Transmission of the example data in JSON format is shown here:
On the client side, consuming the JSON packet requires a decision. If you are trusting,
you might go ahead and evaluate the content as before and create data structures
corresponding to the JSON response:
var responseObject = eval(xhr.responseText);