|
|
|
|
Asynchronous JavaScript And XML, otherwise known as, Ajax is a Web development technique for creating interactive web applications. This is done by making asynchronous calls from the client-side script.
This can lead to an increase in a sites speed and interactivity.
Lets see how:
There are three parts to this.
Part 1. Create the object
Part 2. Use the object to make a request.
Part 3. Get the request.
First one needs to create the object that will make the asynchronous calls.
The Code below has been created for both IE and Mozilla.
//Part 1: Create the object
var objXMLHttp;
var url = "default.asp";
getXMLHttpObject();
function getXMLHttpObject()
{
try
{
objXMLHttp = new XMLHttpRequest();
} catch (trymicrosoft) {
try
{
objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
objXMLHttp = false;
}
}
}
if (!objXMLHttp)
alert("Error initializing XMLHttpRequest");
}
Now one needs to use the object to make a request to the url and set the onreadystatechange event.
//Part 2: Use the object to make a request
function getResponse(strUrl)
{
var stamp = new Date();
objXMLHttp.open("GET", strUrl +"?time="+stamp, true);
objXMLHttp.onreadystatechange = stateChanged;
objXMLHttp.send(null);
}
When the state changes [ie.there is a response to the request] the following function is used to handle it.
//Get the request
function stateChanged()
{
try
{
if (objXMLHttp.readyState == 4
|| objXMLHttp.readyState=="complete")
{
if (objXMLHttp.status == 200
|| objXMLHttp.status ==0)
{
alert(objXMLHttp.responseText);
}else if (objXMLHttp.status == 404){
alert("URL does not exist.");
}else{
alert("unkown error occurred"
+ oobjXMLHttp.statusText);
}
}
}catch (e){}
}
Hope this helps with understanding and getting to know Ajax.
|
|
|
|
|
|