AJAX is a technique rather than a technology: It describes how JavaScript can be used to pull data from the server using the XML HTTP Request object and then insert this data into the website using DOM. This is done asynchronously - that is, in the background, without having to refresh the whole page. The technology which AJAX is based on has already been available for a while, the combination is what makes it new.You can try the examples online or download them and run them locally (except for the PHP script, that would require a webserver with PHP).Simple (html)example shows how to set the content of the
The XML HTTP Request objectThe XML HTTP Request object is used to make HTTP requests. This is the core object that is reqd for doing an AJAX call.
Simple script which shows the required steps for doing an AJAX call.
Combining the Simple Html example with the XMLHttpRequest (above script) gives us AJAX
While the previous example fully demonstrated AJAX, it was totally boring. Including the contents of a static file into the page could have been done much easier, you might say. However, AJAX becomes powerful when combined with a server-sided script. Consider the following PHP script, which validates a user name entered into a form. The name chosen has to be at least three letters long and must still be available:
<?phpfunction validate($name) { if($name == '') { return ''; } if(strlen($name) < 3) { return "<span id=\"warn\">Username too short</span>\n"; } switch($name) { case 'bob': case 'jim': case 'joe': case 'carol': return "<span id=\"warn\">Username already taken</span>\n"; } return "<span id=\"notice\">Username ok!</span>\n";} echo validate(trim($_REQUEST['name']));?>Simple html page, which makes the call to the PHP code….
<script type="text/javascript">var http = false; if(navigator.appName == "Microsoft Internet Explorer") { http = new ActiveXObject("Microsoft.XMLHTTP");} else { http = new XMLHttpRequest();} function validate(user) { http.abort(); http.open("GET", "validate.php?name=" + user, true); http.onreadystatechange=function() { if(http.readyState == 4) { document.getElementById('foo').innerHTML = http.responseText; } } http.send(null);}</script> <h1>Please choose your username:</h1> <form> <input type="text" onkeyup="validate(this.value)" /> <div id="foo"></div></form>http.abort();, which will abort theprevious request, if a new one comes in. This is useful when the user typesvery quickly. The script could probably improved by waiting a couple of secondsafter the user has typed a name. While the server's response is nearlyinstantaneous, this also causes a lot of HTTP requests resulting in a lot ofserver load.
0 Comments:
Post a Comment