Step by Step to AJAX – một bài hướng dẫn khá hay

AJAX has been exciting many programmers as the latest and greatest thing in web development. This article takes a step-by-step look at the Microsoft way to script for AJAX.Introduction This tutorial is not about Ajax Telamon from the Iliad who fought Hercules, but the latest and greatest (at least in the opinion of some) thing in web development. Ever since Google charmed the web at large with those AJAX-created Google Maps apps, the number of amount of adherence to AJAX has been growing exponentially. In this tutorial, we look mainly at the Microsoft way of scripting for AJAX. Like my previous tutorials, it’s step by step all the way after a brief introduction.Web Application Evolution Since 1992 developers have relentlessly pursued ways to make the web more appealing, more productive and more interactive. The plain text html at birth soon saw embedded images followed by appealing colors conferred by cascading style sheets. But it was left for JavaScript to bring user interaction, and thus began the heydays of scripting languages. However, there were two major browsers sharing the web space, and two scripts to serve the user (the third, ECMA came later). This was not enough, and DHTML was born – not a new language, but a good mix of html, CSS, and JavaScript that made user interaction extremely satisfying.AJAX came along to make the interaction more responsive without needing to refresh the page. AJAX is an acronym, and the credit for coining this name goes to Adaptive Path’s S. S. Garret. However, Microsoft appears to be the progenitor, with its flagship ActiveX Technology making this possible. Now it is a mélange of XHTML, CSS, JavaScript, XmlHttpRequest, and XML, and its DHTML déjà vu all over.The figure shown next is derived from Garret’s article on Ajax, redrawn to render it horizontally. The figure shows both the prior art (classic interaction) as well as the AJAX embodiment. In the classic version, the client sends an HTTP(S) request to the server, the server checks to see whether any server side processing is to be carried out, processes the server related instructions and sends back the html with CSS, if it is defined. There is a synchronicity between client request and server response.In the AJAX model, the client sends a JavaScript to AJAX, and AJAX sends the HTTP(S) request to the web server which can also serve XML. The web/XML server sends back the result in the form of XML, and AJAX relies on the Document Object Model (DOM: blue print of web document) to transmit the result in XHTML and CSS. It does so by reading the returned XML’s node tree using DOM. The interaction could be synchronous or asynchronous.One of the key objects needed for working with AJAX is the XMLHttpRequest Object. This object does two things: it handles the httpRequest, and then it processes the XML response. This was implemented in Internet Explorer 5 for Windows as an ActiveX Object. This has been implemented by Mozilla 1.0, Apple and others in compatible forms. The W3C has similar standards for the DOM Level 3 specification. We will take a brief look at this object before we put it to work. Some of the highlighted methods and properties are later used while fetching a web page to show what values they do return.Creating the XML HttpRequest object This is the easy part, if you need to deal only with Microsoft IE. For Mozilla you would instantiate the object using the following syntax:var xhr=new XMLHttpRequest();where as for IE you would use the following:var xhr=new ActiveXObject(“Microsoft.XMLHTTP”);Both of these methods create an object which is hidden from the user. Its methods and properties take control of the server interaction. For cross browser applications you need to come up with a branching syntax. This is not so difficult; see for example the cross-browser boiler plate code (Listing 2.0 in the link)This short list of methods is shared by all supported browsers. In this tutorial we shall look at some of the highlighted methods.abort() current request is stopped getAllResponseHeaders() returns a string containing information of headers getResponseHeader (“headerlabel”) returns a string containing information about a single header open(“method”, “URL”[,asyncFlag[,”userName”[,”password”]]]) assigns various request attributes send(content) Transmits the data with information that may be posted, if needed setRequestHeader (“label”, “value”) assigns label, value pair for the header While open() and send() are most often used, the others are also useful in some cases. The open() method begins the interaction and takes two mandatory arguments; the “method” used to open, which is either GET or POST, and the URL to which the request is made. The GET and POST methods are similar to those used in ASP, as some of you might recognize. The GET is indicated for retrieving read only data while POST is for sending data to the server.The URL could be complete, or a relative URL.The third parameter which is optional (default value TRUE being asynchronous) sets the interaction to be synchronous (FALSE) or asynchronous (TRUE). If you choose the synchronous route, the script waits for the response to arrive before acting. The useful mode is to set the interaction to be asynchronous and use the onreadystatechange event (to be discussed) to get at the response.XMLHttpRequest Object Properties The following read only properties are browser agnostic (all supported browsers understand them).onreadystatechange Event handler which fires every time the state changes readState Integer representing the status of the object0 = uninitialized1 = loading2 = loaded3 = interactive4 = completeresponseText Data returned in string format responseXML Data returned in DOM Compatible format status Numeric code returned by server indicating status404: Not found200: OK statusText Message string that came with the status Working with AJAX is quite simple. The code will be explained by explaining the component parts with reference to an html file, AjaxTest.htm. First you need to create an XMLHttpRequest Object along the lines discussed above. Then you make a request, in this case pass an URL as an argument to the getPage() function. Since you are getting back a page you just need to use the GET argument. Since an asynchronous interaction is intended, use TRUE for the third argument in the open() method. Before the open() method is called the onreadystatechange eventhandler calls the statusCheck() function, where the readyState of the request is verified and the status code is verified to return OK. Both of these functions are in the <Head/> and are evaluated before the rest of the page is loaded. Review the two functions just described for the html page AjaxTest.htm. Some of the properties and methods previously described and highlighted are also returned. The script that follows this paragraph is in the <head/> section of AjaxTest.htm.You also include code to alert you if, for some reason, the XMLHttpRequest object instantiation failed. It also needs to alert the user if the request failed because the page was unavailable, or the server was not responding, or for any other reason.If the status is OK and the readyState shows completion, then you get the response, for this example, in the text format. Now you invoke the DOM API to get the element whose ID=”x”, in this case the <div/>, and set its innerHTML property the same as the returned text. If you look at the response produced by the alert(xhr.responseText) you would see the html of the page you requested as shown in the next picture. I particularly like the preference to use the ECMA scripting style.<SCRIPT LANGUAGE=javascript><!–var xhr = false;function getPage (url) {xhr = false;//this is the Microsoft browser compatible instantiationxhr = new ActiveXObject(“Microsoft.XMLHTTP”);if (!xhr) {alert (‘XMLHttpRequest failed to instantiate’);return false;}xhr.onreadystatechange = statusCheck; (‘GET’, url, true);xhr.send (null);}function statusCheck() {txt1.value=”XmlHttpRequest_Status: ” + xhr.status;txt2.value=”XmlHttpRequest_readyState: ” + xhr.readyState;TEXTAREA1.value=”XmlHttpRequest_getallResponseHead ers(): ” + xhr.getAllResponseHeaders();txt5.value=”XmlHttpRequest_statusText: ” + xhr.statusTextif (xhr.readyState == 4) {if (xhr.status == 200) {alert(xhr.responseText);document.getElementById(“x”).innerHTML =(xhr.responseText);} else {alert (‘There was a problem with the request.’);}}}//–></SCRIPT>However, when you use the DOM API, you get the following as shown:The <body/> of the AjaxTest.htm consists of just the following controls so that the properties, the methods and their values can be displayed. The onclick event starts the process rolling. Of course the <div/> is where the innerHTML property gets written. The html for these controls is as shown:<P><STRONG><SPAN style=”FONT-SIZE: large; COLOR: red”>A</SPAN>synchronous <SPAN style=”FONT-SIZE: large; COLOR: red”>J</SPAN>avascript <SPAN style=”FONT-SIZE: large; COLOR: red”>A</SPAN>nd <SPAN style=”FONT-SIZE: large; COLOR: red”>X</SPAN>ML= <SPAN style=”FONT-SIZE: large; COLOR: blue”>AJAX</SPAN></STRONG></P><P> </P><P> </P><P><INPUT id=button1 type=button onclick=”getPage (‘http://xphtek/TestXMLHttp/Greeting.asp&#8217;)” value=”Get the page by XmlHttpRequest” name=button1></P><P><INPUT id=txt1 style=”WIDTH: 396px; HEIGHT: 22px” size=51></P><P><INPUT id=txt2 style=”WIDTH: 395px; HEIGHT: 22px” size=50></P><P><TEXTAREA id=TEXTAREA1 style=”WIDTH: 393px; HEIGHT: 72px” name=TEXTAREA1 cols=42></TEXTAREA></P><P><INPUT id=txt5 style=”WIDTH: 389px; HEIGHT: 22px” size=50></P><div id=”x”></div>As previously mentioned you can reference the URL completely, as in http://xphtek/TestXMLHttp/Greeting.asp or simply by its relative URL Greeting.asp. The Greeting.asp page is a simple page as shown:<%@ Language=VBScript %><HTML><HEAD><**** NAME=”GENERATOR” Content=”Microsoft Visual Studio 6.0″><script language=”javascript”>document.write (document.lastModified);</script></HEAD><BODY><%Response.Write(“<b>Welcome to programming with AJAX</b>”)%><br><% =Date()%><br>Hello<br></BODY></HTML>Summary The tutorial has looked at the various properties and methods of this interesting XMLHttpRequest object. It goes without saying that the browser should support JavaScript, and as a developer you should appropriately warn the user to enable JavaScript, if it is not. For Microsoft IE there is the additional requirement of browser support for ActiveX objects. For recent browsers the older method of using iframes to update parts of a page will be replaced. However iframes may still find favor with much older browsers. In this tutorial we saw most of the properties, but the lastmodified property returned null; the syntax was double checked but to no avail. Although AjaxTest.htm was coded on Visual Interdev 6.0, it is not a requirement; plain Notepad should work as well.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: