|
XMLHttpRequest and XULXMLHttpRequest has become the spearhead of the new web revolution. In this article we will explore and understand the simplicity of its use. The only AJAX method you will ever need
function WebMethod(url,request,callback)
{
var http = new XMLHttpRequest();
var mode = request?"POST":"GET";
http.open(mode,url,true);
if(mode=="POST"){http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');}
http.onreadystatechange=function(){if(http.readyState==4){callback(http.responseText);}};
http.send(request);
}
Cross-browser instantiationFor the purposes of learning XUL in Mozilla browsers, our direct approach will suffice.
function getXmlHttpObject(){
var http=false;
try {http=new XMLHttpRequest();} catch (e1){
try {http=new ActiveXObject("Msxml2.xmlhttp");} catch (e2){
try {http=new ActiveXObject("Microsoft.xmlhttp");} catch (e3){http=false;}}}
return http;
}
Asynchronous callsIt is absolutely imperative that we use asynchronous calls in our server trips, internet latency makes synchronous calls an ugly alternative we should avoid at all cost.
http.open(mode,url,true); // Asynchronous
or
http.open(mode,url,false); // Synchronous
In a synchronous way, we open the connection, we send the request and wait for the response in the same line, locking the browser from any user interaction until the response arrives.
http.open(mode,url,false); // Synchronous request
http.send(request); // Locked until response returns
alert(http.responseText); // Then next line executes
Two-Step DanceAsynchronous calls can only be achieved in a two step process: send the request and forget about it, the callback function will receive the response whenever it is ready. Here is where our beautifully crafted WebMethod function comes handy:
function LoadMail(){
// ShowMail is the callback function that will receive the response
WebMethod("example.com/getmail.php","folder=inbox",ShowMail);
}
function ShowMail(response){
// do stuff with response
alert(response);
}
It may be a little difficult at the beginning to understand the concept of two step asynchrony Get or PostThe most used http modes are GET and POST and we made it easier for you to make the appropriate request.
// GET mode, parameters in url
WebMethod("example.com/getmail.php?folder=inbox",null,ShowMail);
// POST mode, parameters as request
WebMethod("example.com/getmail.php","folder=inbox",ShowMail);
Well folks, we have covered everything you should know to get you up and running. I hope you have enjoyed this introductory essay on XMLHttpRequest and XUL. George Nava - 2005.11.11 |
||||||||
| Webmaster at GeorgeNava.com | |||||||||