SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 154 | Next

Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb

"Accelerated DOM Scripting with Ajax, APIs, and Libraries"


CHAPTER 5 n AJAX AND DATA EXCHANGE 100
The process of making an Ajax request is fairly straightforward. Here??™s a quick example
put together for you:
// Use the native version for everybody but IE6<
if(window.XMLHttpRequest) {
transport = new XMLHttpRequest();
}else{
try{ transport = new ActiveXObject("MSXML2.XMLHTTP.6.0"); }catch(e){}
try{ transport = new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){}
}
if(transport)
{
transport.open("GET", "http://example.com/test/", true);
transport.onreadystatechange = function(){ alert('I am back!'); };
transport.send();
}
This is the basic structure of an Ajax request. The first part instantiates the XHR object,
beginning with trying to instantiate a native version of the object. If a native implementation
is not found, it attempts to instantiate the ActiveX objects for Internet Explorer (IE). (You??™ll
learn more about why we check for both implementations later on.)
The second part takes the object and opens a connection with three parameters: the
first specifies the method (GET or POST), the second is the URL you want to open, and the
third determines whether the call should be synchronous or asynchronous.
If the third parameter is set to synchronous (false), the browser will wait for the call to
return before users can do anything. This isn??™t ideal because users might think their browser
has frozen and needs to be shut down. Setting it to true makes the call asynchronous, enabling
the user to return to interact with the page while the call processes in the background.


Pages:
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166