AJAX - The Complete Reference

(avery) #1

Chapter 2: Pre-Ajax JavaScript Communications Techniques 43


PART I


Now that we have shown the basics of how the data is sent, we next address any
network issues and, of course, the response data. Given that the server may never respond,
it is necessary to define a timer to alert the user and clear the request if it takes too long.

var timeout;
networkTimeout = function(){cancelRequest(target, "Network timeout",currentRequest);};
timer = setTimeout("networkTimeout()",timeout);

In the case that the response does not timeout, there are two possible approaches to
wake up the client JavaScript. One approach is to bind an onload event to the inline frame.

currentRequest.onload = function () {handleResponse();};

NNOT EOTE Event handling in JavaScript is one of the least consistent things across browsers. The
previous example illustrates the general idea, but the specific syntax will vary greatly by browser.
For example, IE will prefer the attachEvent() method, and DOM aficionados might desire to
add event listeners. Given the inconsistencies, we will aim to use the most basic approach even if
more advanced possibilities are available.

The other option is to have the server-side generate the appropriate function call in its
response to directly invoke the handleResponse function in the parent frame. For example,
here parameters are set in the payload to indicate that the response should contain script
code back that invokes the handleResponse function.

payload += "&callback=handleResponse";
payload += "&response=script";

The communication trace found in Figure 2-6 shows clearly that the server responds
with an iframe that invokes the callback function in the parent document.
You can explore the use of iframes with GET and POST requests at http://ajaxref.com/
ch2/twowayiframeget.html and http://ajaxref.com/ch2/twowayiframepost.html,
respectively.

Sending and Receiving Other Data Formats
Inline frames don’t just have to send and receive script code as has been previously
demonstrated. It is also possible to use HTML fragments, XML, or even another data format
such as serialized JavaScript (JSON). Figure 2-7 shows two different network traces showing
data transmissions in such alternate forms.
Now before you get excited and start passing XML or other data formats around, carefully
consider that you will have to potentially decode and consume this received content, which
may be quite a chore. As an illustration consider that the ratings application might pass back
an XML packet like:

<pollresults>
<rating>5</rating>
<average>3.08</average>
<votes>1036</votes>
</pollresults>
Free download pdf