AJAX - The Complete Reference

(avery) #1

Chapter 2: Pre-Ajax JavaScript Communications Techniques 39


PART I


While the image cookie technique would seem to solve the need for two-way data
transmission, do note that this technique has a major weakness: if cookies are turned off, it
is going to fail.

Two-way Script Tag Communication

As you might recall, adding a <script> tag to a document can invoke a request, and it will
expect script code back as a response.

var newScript = document.createElement("script");
newScript.src = url+"?"+payload;
newScript.type = "text/javascript";
document.body.appendChild(newScript);

In this case, we indicate in the request payload that JavaScript code should be returned and
that the code generated should invoke a call to the callback function requestComplete() so
that it can consume any returned data.

/* form query string with rating,transport,callback,and response type */
var payload = "rating=" + encodeValue(rating);
payload += "&transport=script";
payload += "&response=script";
payload += "&callback=requestComplete";

On the server side, the user-passed data is read and a result calculated just as in
previous examples. However, this time returning a result is a matter of forming a function
call and outputting it, as shown here:

if ($response == "script")
{
$message .= "$callback('$rating','$votes','$average');";
print $message;
exit;
}
Free download pdf