Alternate Ajax Techniques, Part 2
Alternate Ajax Techniques, Part 2
In the last installment of this series, you learned about dynamic
script loading, which involves creating a <script/>
element
dynamically and using it load JavaScript from the server. To make that work,
your browser had to be DOM-compliant. In Part 2, you'll learn how to use images
and cookies to enable client-server communication even on older browsers that
don't support the DOM.
Images and Cookies
When people think about cookies nowadays, most think about security concerns, spyware and evil corporations tracking their every move. Those fears are understandable given what goes on in the world of the Web, but cookies really are just small pieces of data that can be accessed by both the client (through JavaScript) and the server. However, there are several restrictions placed on cookies that you need to be aware of before using them:
|
Since Netscape Navigator 3, you've been able to change the src
attribute of an image using JavaScript. This counts as a request and, therefore,
brings with it cookie information from the server. As it turns out, images also
fire a load event when the image has completely finished loading, allowing you
to know exactly when the data you requested is ready. This makes images an ideal
way to manipulate cookies for client-server communication.
The Technique
The basic technique behind using images and cookies is similar to preloading
images. You need to create a <img/>
element and then assign
its src
attribute. To tell when the image is loaded, assign an
onload
event handler:
var oImg = document.createElement("img"); |
<script/>
element, the download
of an image begins as soon as the src
attribute is assigned, meaning
that you don't even need to add the image to the page. In fact, you don't even
need to use an <img/>
element at all, you can use the Image
object:var oImg = new Image(); |
onload
event handler. The getCookie()
method gives
you easy access to specific cookie values:function getCookie(sName) { |
document.cookie
returns
a series of name-value pairs that are URL-encoded and separated by semicolons.
This function looks through the string for the value matching the given name.
Created: March 27, 2003
Revised: March 17, 2006
URL: https://webreference.com/programming/ajax_tech2/1