Page 3 of
6
<< Previous
1 2
3 4
5 6
Next >>
|
AJAX (Asynchronous JavaScript And XML) Tutorial
Using the XMLHttpRequest Object - Client Side JavaScript Code
|
This example assumes you are familiar with some basic JavaScript code.
Earlier I said AJAX was supported by all major browsers. While this is true,
they support it in different manners. Internet Explorer uses its
ActiveXObject to support the XMLHttpRequest object while other
browsers use the intrinsic XMLHttpRequest JavaScript
object. To complicate things further, different versions of IE call this object
or ProgId by different names, either Msxml2.XMLHTTP
or Microsoft.XMLHTTP.
This means we need a JavaScript function that will work in all browsers and
create the correct XMLHttpRequest object. The CreateXMLHttp
does this basically by trial and error. If successful, it populates the XMLHttp
variable with the XMLHttpRequest object.
There are two other JavaScript functions listed here. The HandleResponse
function does as its name implies and handles the response of the
XMLHttpRequest object by cecking its readyState property
for a status of 4 - request complete.
Once the request has completed, we need to check that a valid response was
received. The status property holds the HTTP
status code returned from the server. A value of 200 means that the data
received in the request is good. We must verify we did not receive an HTTP
status code of 404 (page not found), 403 (access forbidden), and 500 (internal
server error), etc.
<html>
var XMLHttp;
function CreateXMLHttp()
{
try
{
XMLHttp = new XMLHttpRequest();
}
catch (e)
{
try
{
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
try
{
XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
return false;
}
}
}
}
function HandleResponse()
{
if(XMLHttp.readyState == 4)
{
if(XMLHttp.status == 200)
{
var theValue = document.getElementById("stateName");
theValue .value = XMLHttp.responseText;
}
else
{
alert("Unable to get the data from the server. Readystate: " +
XMLHttp.readyState + " Status: " + XMLHttp.status);
}
}
}
function ajaxGetValue()
{
var clientValue = document.getElementById("stateAbbreviation");
var requestUrl = "AjaxServerPage.aspx?val=" + clientValue.value;
CreateXMLHttp();
if(XMLHttp)
{
XMLHttp.onreadystatechange = HandleResponse;
XMLHttp.open("GET", requestUrl, true);
XMLHttp.send(null);
}
}
The last function shown is the ajaxGetValue function.
This is the function that gets called from your web page. It is responsible for
getting the value the user enters, creating the URL of the server pagr that
does the actual processing, calling the CreateXMLHttp function to create the
XMLHttpRequest object, and then calling the HandleResponse function to get the
data returned from the server and updating the web page. This function will get
a bit clearer when you read the next page.
|
Page 3 of
6
<< Previous
1 2
3 4
5 6
Next >>
|
|
About TheScarms
Sample code version info
|