JavaScript Remote Scripting: Processing XML Files - Reading XML files with AJAX: defining the “sendRequest()” function
(Page 3 of 6 )
If you’ve read the first part of this series, the “sendRequest()” function should be already pretty familiar. Essentially, it performs two well-delimited tasks: the first one consists of instantiating cross-browser XMLHttpRequest objects, while the second one is responsible for sending the proper http request and fetching the contents of the file passed as a function argument. Here is its definition:
function sendRequest(doc){
// check for existing requests
if(xmlobj!=null&&xmlobj.readyState!=0&&xmlobj.readyState!=4){
xmlobj.abort();
}
try{
// instantiate object for Mozilla, Nestcape, etc.
xmlobj=new XMLHttpRequest();
}
catch(e){
try{
// instantiate object for Internet Explorer
xmlobj=new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e){
// Ajax is not supported by the browser
xmlobj=null;
return false;
}
}
// assign state handler
xmlobj.onreadystatechange=stateChecker;
// open socket connection
xmlobj.open('GET',doc,true);
// send GET request
xmlobj.send(null);
}
In simple terms, the above defined function is flexible enough to handle multiple data formats, so it’s not only restricted to reading XML files. Notice that the “doc” argument could be any file feasible for being processed through a GET request, a feature that turns the function into a very versatile piece of code.
Also, by studying the snippet a little bit deeper, it becomes clear that it allows for the fetching of content that is dynamically generated. Instead of passing in only the name of the file to be fetched, it’s possible to append some variables to the querystring, because it’s done with regular links. For instance, if the requested file is “script_file.php”, it’s extremely easy to add a few parameters for processing on the server, in the form “script_file.php?param1=1¶m2=2”. I guess this is enough of an explanation for you to start tweaking the code to pull out dynamic content.
Having explained how the “sendRequest()” function does its business, it’s time to take a look at the next function “stateChecker()”, which as you’ll see in a moment, controls the flow of the whole program.
Next: Checking the progress of a request: a quick look at the “stateChecker()” function >>
More JavaScript Articles
More By Alejandro Gervasio