22 Part I: Core Ideas
One-way Iframes with Query Strings
There are many other ways to send information to the server besides making image
requests. In fact, just about any tag that references an external URL can be used. For
example, inline frames, as defined by the <iframe> tag, also support a src attribute to load
a document. Using this construct it is possible to employ a similar communication
technique as was employed with images. Consider adding an invisible inline frame in the
page, like this one:
<iframe id="hiddenIframe" style="visibility:hidden;"></iframe>
Now find this tag using a DOM call and set its src value to the server-side program
that should be invoked along with a query string containing the data to be transmitted.
var ifr = document.getElementById("hiddenIframe");
ifr.setAttribute("src",url);
It isn’t necessary to preload the iframe into the page, the DOM can be used to insert it
dynamically. The following rewrite of the sendRequest function replicates the previous
image-based communication rating example but uses DOM inserted inline frames instead:
function sendRequest(url,payload)
{
var ifr = document.createElement("iframe");
ifr.style.visibility="hidden";
document.body.appendChild(ifr);
ifr.src = url+"?"+payload; // set src last to avoid double fetch
}
When you run the example (http://ajaxref.com/ch2/onewayiframeget.html), notice that
your browser will likely show an indication of network activity, which may not be desirable.
NNOT EOTE Depending on the browser and how you have coded your iframe-based communication, it is
possible that the iframe activity will be saved in your browser’s history. In Chapter 9 this “quirk”
may turn out to be a good thing that helps fix problems with Ajax and the back button, but in a
one-way communication pattern it may not be desirable.
One-way Script Tags
The <script> tag also has a src attribute that can be used to make a request. Normally the
server would respond with script code to be executed, which could be empty, but in this
case it will do nothing, as it will receive a 204 response. The technique is roughly the same
as the previous inline frame example, but the sendRequest function looks like this:
function sendRequest(url,payload)
{
var newScript = document.createElement("script");
newScript.src = url+"?"+payload;
newScript.type = "text/javascript";
document.body.appendChild(newScript);
}