AJAX - The Complete Reference

(avery) #1

150 Part I: Core Ideas


With the data now in hand, populate the page in a similar fashion as previous
examples:

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

The YAML response example can be found at http://ajaxref.com/ch4/yamlresponse.html.

Script Responses


Given that in a typical Ajax application we are receiving and consuming data in JavaScript,
it would seem appropriate to consider it or a related format for transport. We see that to be
quite an attractive solution in the next few sections, but be warned that such approaches do
have security considerations that must be mitigated as will be discussed in Chapter 7.

Raw JavaScript
Like the earlier examples where markup fragments are passed back and directly used, given
that JavaScript is the receiving technology it seems reasonable and appropriate to simply
pass back script to execute. This is quite easy to do as illustrated by this PHP fragment:

header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: application/x-javascript");
$message = "var responseOutput = document.getElementById(\"responseOutput\");
responseOutput.innerHTML += 'Thank you for voting. You rated this a
<strong>$rating</strong>. There are <strong>$votes</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>';";

echo $message;

Transmission also looks exactly as you would expect:
Free download pdf