AJAX stands for Asynchronous JavaScript And XML. All it really consists of is JavaScript, just like you would have in any other application, and an XMLHTTP connection to your web server. That's it! The general idea is that when you need to pull data from a server you can just go and get the specific data you need instead of refreshing the entire page.
To start with, AJAX almost always relies on a server-side language such as PHP or ASP. When your users need to get new data, the JavaScript requests it, and the server will probably query a database and then return the data. This data can be returned in several forms. If it is structured, then you will generally have XML or JSON data. If it is very simple data (such as getting a description for an item), you will often see people just writing that data directly to the AJAX response.
The first thing we need to do when creating an AJAX request is to create an XMLHTTP object. Netscape/Firefox, Opera and other browsers have this object built-in. Internet Explorer uses an ActiveXObject. So we create one function that works for all of these browsers:
var XMLHttpRequestObject = createXMLHttpRequestObject();
function createXMLHttpRequestObject()
{
var XMLHttpRequestObject = false;
try
{
XMLHttpRequestObject = new XMLHttpRequest();
}
catch(e)
{
var aryXmlHttp = new Array(
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP",
"MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0"
);
for (var i=0; i<aryXmlHttp.length && !XMLHttpRequestObject; i++)
{
try
{
XMLHttpRequestObject = new ActiveXObject(aryXmlHttp[i]);
}
catch (e) {}
}
}
if (!XMLHttpRequestObject)
{
alert("Error: failed to create the XMLHttpRequest object.");
}
else
{
return XMLHttpRequestObject;
}
}
Connect with PHP
function getData(dataSource, divID)
{
if(XMLHttpRequestObject)
{
dataSource += "&parm="+new Date().getTime();
var objDiv = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
try
{
switch(XMLHttpRequestObject.readyState)
{
case 1:
objDiv.innerHTML = '<br><br><img src=../background/index/loading.gif alt=Loading...><br>Loading...';
break;
case 4:
if(XMLHttpRequestObject.status == 200)
{
objDiv.innerHTML = XMLHttpRequestObject.responseText;
}
else
{
objDiv.innerHTML = 'Error getting from php result...';
}
break;
}
}
catch(e){}
}
try
{
XMLHttpRequestObject.send(null);
}
catch(e){}
}
}
For more info., go check http://www.htmlgoodies.com/primers/jsp/article.php/3608046
No comments:
Post a Comment