A Hype-Free Introduction to Ajax
←
→
Page content transcription
If your browser does not render page correctly, please read the page content below
A Hype-Free Introduction to Ajax by Chris Schalk Get an overview of the core fundamentals of Ajax, without the usual hype. Published April 2006 You've probably heard all the Ajax hype by now, as well as seen the many products that claim Ajax support or "compliance." However, you probably haven't seen a good, simple technical explanation of what Ajax really "is." In this article, you'll get an overview of the core fundamentals of what makes Ajax possible without all the usual product-pushing hype. First of All, is Ajax New? Not really. Remote Javascript, of which Ajax is one example and which has garnered the most attention as of late, provides the ability to interact with a server using XML data. Ajax is possible because of the leading browsers now offering objects that can make independent XML HTTP requests. Internet Explorer 5 and later offer an XMLHTTP object while Mozilla based browsers provide an XMLHttpRequest object. Both these objects offer essentially the same ability to request XML data from a server and process the data in a similar fashion. The server-side Ajax component can be in any technology providing XML can be delivered dynamically. Any dynamic Web technology ranging from PHP to servlets can serve as an Ajax server. One of the drawbacks to Remote Javascript and Ajax is that it forces the page author (the person designing the final page) to develop a fair amount of Javascript code that manages the XMLHTTP interactions. Fortunately, JavaServer Faces (JSF) provides a solution here and makes Ajax very easy to use. Ajax Under The Hood Before reviewing more advanced examples of Ajax integrated with other technologies, such as with JSF, it is useful to understand the core Ajax architecture involved in an Ajax client-server transaction. Ajax is possible providing the two core technologies are present: • A Javascript-enabled browser that supports either XMLHTTP or XMLHttpRequest objects • An HTTP Server technology that can respond in XML Because all the popular browsers support Javascript and the necessary XMLHTTP request objects and almost any Web server technology can generate XML (or any markup), the core Ajax technology is widely available. An Ajax application in its simplest form is essentially a standard HTML user interface with Javascript functions to interact with an HTTP server that can generate XML dynamically. Any dynamic Web technology ranging from CGI to servlets—including JSF as we’ll review later—can serve as a server- side Ajax technology. The key elements of a core Ajax application are: • An HTML page that contains:
• UI elements that interact with Ajax Javascript functions • Javascript Functions that interact with Ajax server • A server-side Web technology that can process HTTP requests and respond in XML markup. These elements are also shown in Figure 1. Figure 1 Core Ajax architecture Reviewing the key elements, we have an HTML user interface with elements such as an input field, a button or anything that can be linked to Javascript. For example, a button could fire a Javascript function when pressed, or for even more subtle usage an input field could fire a Javascript function as the user types into the field. For this you could set an onkeyup= to the value of the Javascript function to process the data in the input field. For example, the input field “searchField” will call the Javascript function lookup( ) when an onkeyup event occurs (i.e. during typing). In addition to responding to user interface interactions (like typing), Ajax Javascript functions they can operate independently on their own timers. (An Ajax autosave feature can be implemented using this approach.) How to Issue an XML HTTP Request Now that we’ve reviewed how the Ajax Javascript code can be invoked, let’s review the actual code in Javascript that can issue an XML HTTP request: if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } This code snippet allows both major browser families (Internet Explorer and Mozilla/Safari) to make independent HTTP requests to servers. This code first checks to see if the browser supports either of
the supported XMLHTTP objects and then instantiates one. Once an XMLHttpRequest (or Microsoft’s XMLHTTP) object has been instantiated, it can be operated on in exactly the same manner. To initialize a connection to a server, the open method is used: req.open("GET", url, true); The first argument is the HTTP method (GET or POST). The second argument is the URL of the server (or form action is using a POST) and the third argument when true denotes whether the call should be made asynchronously (The “A” in Ajax). This means that the browser can continue doing other things while the request is being fulfilled. A false value in the open method denotes a non- asynchronous or serial processing. This is not recommended, as your browser will cease operations until the response has been returned. After initializing a connection using open, the onreadystatechange call is made (only for asynchronous calls). This registers a callback function, which will be invoked once the request is complete: req.onreadystatechange = processXMLResponse; The function processXMLResponse( ), which processes the XML response, is invoked when the request is fulfilled. A callback function can also declared inline in the onreadystatechange statement: req.onreadystatechange = processXMLResponse() { // process request }; Any header content can also be specified using req.setRequestHeader. Such as: req.setRequestHeader("Cookie", "someKey=true"); Once the XMLHTTP request object (req) has been fully initialized, initiating a call to the server can be done using send( ): req.send(null); For GET requests, a null value or empty string “” is used. POST requests contain a string argument with form data. They also require the Content-Type to be set in the header of the request. The following two lines show how to perform a Ajax POST request: req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"; req.send("name=scott&email=stiger@foocorp.com"); The callback function, which is called once the request has been fulfilled, usually has some code to make sure the request has not error-ed out. This can be accomplished by checking the readyState as well as the overall status of the HTTP request. (A readystate of 4 means the XMLHTTP request is complete and 200 means it was a success (as opposed to 404 etc.). function processXMLResponse() { if (req.readyState == 4) {
if (req.status == 200) { // Process the XML response } } } Processing the XML response is done using standard Javascript DOM methods. For example, to extract the employee name from the incoming XML stream: Chris You can use the following: var name = req.responseXML.getElementsByTagName("employee")[0]; Parsing more complex XML involves iterating through the elements using code such as: for (i=0;i
Chris Schalk [blog] is a principal product manager and Java evangelist for Oracle's application server and development tools division. Chris' primary expertise is Web application development and he is responsible for defining the Web development experience for Oracle JDeveloper.
You can also read