AJAX - The Complete Reference

(avery) #1

42 Part I: Core Ideas


Like many things in Web development, just because you can do something, doesn’t
mean you should. However, if you must see this communication hack in all of its glory, visit
http://ajaxref.com/ch2/twowaystyle.html.

Two-way Iframes

As seen in the one-way communication patterns discussion, the iframe method is quite
flexible since it supports the posting of data, but in the two-way pattern, there are many
other benefits. First, note that the iframe is flexible in what it can receive compared to some
of the previously discussed methods. Usually it will receive either plain markup (XHTML
or XML) or markup with some script code to run. However, in theory just about anything
could be returned. Of course, this may be dependent on how the browser handles the MIME
type it is receiving and, sorry to say, not all browsers are terribly well behaved. Second,
similar to the Image object, it is possible to bind an onload handler to an iframe to wake up
on data receipt. Unfortunately, there is no error handling or timeouts intrinsic to the object,
which would be useful.
As with the one-way iframe pattern, if the GET method is being employed, the first step
is to use the DOM to create the tag to be used for communication and then set its source to
the target server-side URL with the appropriate query string.

var currentRequest = document.createElement("iframe");
currentRequest.style.visibility="hidden";
document.body.appendChild(currentRequest);
currentRequest.src = url+"?"+payload;

In contrast, if the request is using the POST method, the iframe is still made, but instead
you will create a form that holds form fields equal to the name-value pairs of the payload
being submitting to the server, as shown in this code snippet:

// ifrDoc is a correct reference to the iframe’s Document object
var ifrForm = ifrDoc.createElement("FORM");
ifrForm.action = url;
ifrForm.method = "post";
ifrDoc.body.appendChild(ifrForm);
for (var key in payload)
{
var ifrText = ifrDoc.createElement("INPUT");
ifrText.type = "text";
ifrText.name = key;
ifrText.value = encodeValue(payload[key]);
ifrForm.appendChild(ifrText);
}

Once given this form you simply submit it to start the communication.

ifrForm.submit();

NNOT EOTE One important aspect of posting data to a server rather than using a query string is that
well-behaved caches will not cache the response.
Free download pdf