AJAX - The Complete Reference

(avery) #1

Chapter 2: Pre-Ajax JavaScript Communications Techniques 19


PART I


the image request not only tries to fetch an object, but also sends some information via the
query string parameters. To transmit data this way, it is not necessary to resort to direct
embedding of the image into the page using XHTML; instead JavaScript can do so
dynamically. Traditionally in JavaScript this would be performed by creating an instance of
the Image object.

var img = new Image();

Next, the instantiated object’s src property would be set to the URL in question,
making sure that the query string indicates the appropriate rating.

var url = "http://ajaxref.com/ch2/setrating.php?rating=3&transport=image";

img.src = url;

That’s it, the communication is complete. Notice that it isn’t even required to include the
returned image in the page at all.
It is also possible to use DOM-style methods to perform the same task as previously
discussed, but such methods add nothing in terms of functionality. The same approach
using such methods is shown here:

var img = document.createElement("img");
var url = "http://ajaxref.com/ch2/setrating.php?rating=3&transport=image";
img.setAttribute("src",url);

To illustrate the full process of image-based communication, a complete example is
presented here:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Chapter 2 : Image Rating - One Way</title>
<script type="text/javascript">

function sendRequest(url,payload)
{
var img = new Image();
img.src = url+"?"+payload;
}
function rate(rating)
{
/* string identifying type of example making rating */
var transport = "image";
/* URL of server-side program to record rating */
var url = "http://ajaxref.com/ch2/setrating.php";
/* form query string with rating and example id string */
var payload = "rating=" + escape(rating);
payload += "&transport=" + escape(transport);
/* submit rating */
sendRequest(url,payload);
Free download pdf