AJAX -Introduction and Overview
Ημερομηνία: 08/04/2013
Δεν έχετε συμπληρώσει όλα τα απαιτούμενα στοιχεία
Το email που δώσατε δεν είναι σωστό
Imagine yourself being a web developer a few years ago. Suppose you had a page full of data, among which there was one small part which had to be refreshed. There was only one way to do this. The server had to post the whole of the page back to the client. That was no good at all. Not only did you have to wait for the server to create the page all the way from the begining and send it back, but you could also easily disrupt the client from what he was doing.
That was the reason developers came up with a technique that came to be called AJAX. So what does this AJAX thing do? Instead of fetching the entire page, asynchronously you get only the part of the page you want to refresh. If your page contains twenty data representations you use JavaScript to ask the server for only one of them. The server will return the resource you ask for and then you replace your existing representation with the new one.
More AJAX
That's the idea. Using AJAX you only get the part of the page you want to refresh. No more postbacks. And what's more? The user won't feel a thing.
AJAX stands for Asynchronous JavaScript and XML. What do we get by this?
- Asynchronous refers to the fact that what you ask and the server's response need not follow up the usual way of requesting a page and wait till other server operations are finished. It all happens at the same time.
- JavaScript stands for JavaScript, the well- known client side language which we use in order to ask the server and to handle the resource we are given.
- XML stands for XML, as the way of sending the resources back to the client. Back to the time when the name AJAX was first used, developers imagined that the data requested would be sent always in the form of an XML file and the client would use JavaScript to represent the information. That proved wrong as it soon became evident that many developers would response in the form of already created html parts or JavaScript objects ( a technique known as
JSON).
Creating an AJAX application
In order to create a simple AJAX application you do not no need server side controls or languages like C# or VB. Well, if you want to get serious you will need to have some server side code running, but to create a simple example all we need is JavaScript.
First, we are going to create a method called loadXML which will create an XMLHttpRequest object.
xmlhttp = new XMLHttpRequest();
This object we will use to exchange data with the server.
Lately all browsers support XMLHttpRequest. Old browsers like IE version 6 and older did not support it and you had to check for browser compatibility before advancing, like this
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
You may optionally insert this check in your script just in case a browser does not support XMLHttpRequest or the user has switched it off himself, to make sure that your script will not fail.
Now, what to do with this? Let's give it all the info it needs (open) and send it to the server (send).
The open method looks something like that.
xmlhttp.open(requestType, url, isAsynchronous);
-
requestType can be set to "GET" or "POST". You can choose the http method you wish, the same way you would when you would make an actual request.
-
url is the server's url you are about to hit. If the requestType is set to "GET" you can also send info using the query string.
-
isAsynchronous can be set to true or false. Since using asynchronous calls is much more efficient, it is not recommended to choose false, unless this is what you want.
For example:
xmlhttp.open("GET", url, true);
OK, now we send our XMLHttpRequest object.
xmlhttp.send();
Handling the response
Before we can show our precious info we have to make sure that the response is ready. In order to do so we will use the onreadystatechange event. This event will store a function that is to be called when the XMLHttpRequest's readyState changes.
What is the readyState? It is an XMLHttpRequest property that takes only five different values. Depending on the value, the XMLHttpRequest's status can be
0 |
request not initialized |
1 |
server connection established |
2 |
request received |
3 |
processing request |
4 |
request finished - response is ready |
That means that till our readyState turns to 4 there is nothing we can do.
There's still one more thing we have to check before we can be sure to move on. The XMLHttpRequest status property. This is about the same as the HTTP status code is. So, we are OK only when we get a status of 200 (OK).
To sum up a little bit, what we' ve been talking about in the last paragraph is nothing but this
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//Move on
}
}
We are ready to show what we've collected. If we have requested an xml we should use
XMLHttpRequest.responseXML
If what we have in our hands is pure HTML text we should use
XMLHttpRequest.responseText
We could also use
JSON. In that case we would have to use a different approach to handle the data.
A Useful Example
No more theory. Let's see what AJAX can actually do. We will create a simple example that will read data concerning football match results stored in an XML. The XML will look like that.
<?xml version="1.0" encoding="utf-8" ?>
<scores>
<match>
<Team1>Paris Saint Germain</Team1>
<Team2>Barcelona</Team2>
<results>2-2</results>
</match>
<match>
<Team1>Bayern Munich</Team1>
<Team2>Juventus</Team2>
<results>2-0</results>
</match>
<match>
<Team1>Malaga</Team1>
<Team2>Dortmund</Team2>
<results>0-0</results>
</match>
<match>
<Team1>Real Madrid</Team1>
<Team2>GalataSaray</Team2>
<results>3-0</results>
</match>
</scores>
We suppose that our XML can be updated each time a team scores and the highly dedicated fans that visit our site need to know what the score is at the exact moment. That's where AJAX joins the game.
This will be the method we create to use AJAX.
loadXMLDoc(url)
We will use the following script to call it every ten seconds so the data is automatically refreshed.
//Refresh data every 10 seconds
window.setInterval(function () {
/// call your function here
loadXMLDoc('scores.xml');
}, 10000);
Here's the full code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax</title>
<script type="text/javascript">
function loadXML(url) {
var xmlhttp;
var matchScoresDivText, match, matchTag, counter;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
//Check if you are ready
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//Create a table containing the results
matchScoresDivText = "<table>";
match = xmlhttp.responseXML.documentElement.getElementsByTagName("match");
for (counter = 0; counter < match.length; counter++) {
//Repeat for every match
matchScoresDivText += "<tr>";
matchTag = match[counter].getElementsByTagName("Team1");
{
//Get team1
try {
matchScoresDivText += "<td>" + matchTag[0].firstChild.nodeValue + "</td>";
}
catch (er) {
matchScoresDivText += "<td> </td>";
}
}
matchTag = match[counter].getElementsByTagName("Team2");
{
//Get team2
try{
matchScoresDivText += "<td>" + matchTag[0].firstChild.nodeValue + "</td>";
}
catch(er) {
matchScoresDivText += "<td> </td>";
}
}
matchTag = match[counter].getElementsByTagName("results");
{
//Get the result
try{
matchScoresDivText += "<td>" + matchTag[0].firstChild.nodeValue + "</td>";
}
catch(er) {
matchScoresDivText += "<td> </td>";
}
}
matchScoresDivText += "</tr>";
}
matchScoresDivText += "</table>";
document.getElementById('matchScoresDivID').innerHTML = matchScoresDivText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
//Refresh data every 10 seconds
window.setInterval(function () {
// call your function here
loadXML('scores.xml');
}, 10000);
//Get initial data
loadXML('scores.xml');
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="matchScoresDivID"/>
</div>
</form>
</body>
</html>
This an aspx page but to create this application we could have used a simple html file.
We will get the content of our xml file (scores.xml) using AJAX the way we described earlier.
-
We create an XMLHttpRequest/ ActiveXObject
-
We open and send it
-
We wait till we get the response
-
We go through the xml tags and create an html table which we put in the matchScoresDivID div.
* As this article is not about how to get data using AJAX and not how handle XMLs using JavaScript, I will not explain thoroughly how the XML is processed and the table created.
First, I call my loadXML method manually; then it is called automatically every ten seconds. If we wanted to be more accurate we could minimize the interval. However, keep in mind that too many AJAX requests can slow down your server the same way actual requests would.
Now, supposing Juventus scored, our html would soon change to
This example, though simple it may be, still shows how effective AJAX can be. It is definitely something you should keep in mind when designing large scale sites.
Conclusion
AJAX is a technique used by web applications in order to refresh data representation without asking for a full page response. It uses JavaScript to asynchronously get data in XML or other forms which will later be represented in the page.
Πίσω στο BlogΠροηγούμενοΕπόμενο