Ajax laid a better Web application development road
Related Tags:
Heavy pages to a Web application development in the availability of the biggest obstacles for the development of Java, is a major challenge. In this series, the author introduced by Philip McCarthy background-channel approach to create dynamic Web application experience.
Ajax (Asynchronous JavaScript and XML) is a combination of Java technology, XML, and JavaScript programming technology, allows you to build Java technology-based Web applications, the use of pages and break the heavy-duty practice.
Ajax, for Asynchronous JavaScript and XML is the use of client-side script and the Web server data exchange Web application development methods. In this way, interactive Web pages do not have to interrupt the process of re-plus CD, can be dynamically updated. Using Ajax, you can create closer to a desktop application, direct, high availability, and even richer, more dynamic Web user interface.
Ajax is not a technology, it is more like a model - signs and useful design techniques described a method. For just understand its many developers, it is a new feeling, but all the components to achieve Ajax have existed for many years.
At present the excitement is because, in 2004 and 2005 there have been some very Ajax-based dynamic WebUI, especially Google's GMail and Maps applications, and photo-sharing site Flickr. These UI full use of a Background channel, but also by some developers as "Web 2.0", and lead to everyone interested in the Ajax applications soared.
In this series, I will be all you need is the development of your own Ajax application tools. In this first article, I will explain the concept behind the Ajax model for Web-based applications to create a system of the Basic steps Ajax interface. I will use the sample code to demonstrate the realization of Ajax dynamic interface server-side Java code and client JavaScript scripting. Finally, I would point out that in some ways easy to Ajax mistakes made, as well as in the creation of Ajax application should be considered within the broader context of the availability and easy accessibility of the issues.
A better Cart
You can use Ajax to strengthen the traditional Web applications through the elimination of pages printed in the interaction to make more fluid. In order to model it, I will use a simple, can be dynamically updated by adding items to Cart. With an online store, this method can not wait for the click Heavy pages, and let us continue to browse and select the items to the shopping cart.
Although this code in the cart for example, but the Display can be used other technologies Ajax applications. Table 1 is shown in the examples Cart used by the html code. Throughout this article, I will be applied to these HTML code.
Ajax process
An interactive Ajax from a group called XMLHttpRequest JavaScript objects began. As the name suggests, it allows a client-side scripting to implement HTTP requests, and an XML format will be analytic server response. Ajax the first step in the process is to create a XMLHttpRequest examples. Use HTTP methods (GET or POST) to deal with the request, and will target url to the XMLHttpRequest object.
Now, remember how Ajax in the first asynchronous processing state? When you send HTTP requests, you do not want to wait for the browser and server hung response Instead, the pages you wish to continue to respond to users through the interactive interface and the server response to the arrival of the real deal with them.
To complete it, you can XMLHttpRequest register a callback function, and asynchronous request to distribute XMLHttpRequest. Control immediately be returned to the browser, when the server response arrived, the callback function will be called.
In the Java Web server, at the request of any other HttpServletRequest and the same. Analytical parameters in the request, servlet implementation of the necessary application logic, will respond to the sequence of XML, and write it back to HttpServletResponse.
Return to the client, registration XMLHttpRequest the callback function will now be called by the server to handle the return of XML documents. Finally, the updated user interface to respond to the server from the data transmission, the use of JavaScript to manipulate the pages of HTML DOM. Ajax Figure 1 is a sequential process map.
Figure 1: Ajax process

Now, you should be on the Ajax process with a high-level view. I will enter them every step to see more details of the contents. If you can not find their positions, they go back a look at the plug, and - because of the asynchronous nature of Ajax method, timing diagrams is not straight forward.
Send an XMLHttpRequest
I will be the starting point for Ajax timing diagrams began: from the browser to create and send a XMLHttpRequest. Unfortunately, in different browsers to create XMLHttpRequest method is not the same. Example 2 List of the JavaScript functions and eliminate these types of browser-related issues, and correctly detected with current methods related to the browser, and can use a return to the XMLHttpRequest. It will be regarded as the best backup code, it will be a simple copy to your JavaScript library, in the need for a XMLHttpRequest can use it.
List 2: cross-browser to create a XMLHttpRequest
/ * Return to a new XMLHttpRequest object, if the browser does not support the failure * / function newXMLHttpRequest () (var xmlreq = false; if (window.XMLHttpRequest) (/ / non-Microsoft browser to create XMLHttpRequest object = new xmlreq XMLHttpRequest ();) else if (window.ActiveXObject) (/ / MS ActiveX created through XMLHttpRequest try (/ / attempt by the new method to create xmlreq InternetExplorer = new ActiveXObject ( "Msxml2.XMLHTTP");) catch (e1) (/ / create the ActiveX object request failed try (/ / attempt by the old version InternetExplorer ways to create xmlreq = new ActiveXObject ( "Microsoft.XMLHTTP");) catch (e2) (/ / ActiveX can not create XMLHttpRequest))) return xmlreq;)
Later, I will discuss how to deal with do not support the browser XMLHttpReauest some skills. Now, the list two examples of function in the display will always be able to return to a XMLHttpReauest examples.
Back to the example of the cart scenes, as long as users for a directory entries clicking on the Add to Cart button, I would like to call an Ajax interaction. Called addToCart () function through Ajax onclick call (such as shown in table 1) to update Cart state.
In Table 3, addToCart () the first thing to do is to call newXMLHttpReauest function (such as shown in table 2) to obtain an XMLHttpRequest example, and register a callback function to accept the server response (I explained in detail later, please refer to the list 6).
This is because, this request would alter the server status, I will use an HTTP POST to deal with it. POST data transmission needs through three steps: First, I need to open a communication server resources POST connections - now is an example URL mapping for the server-side cart.do servlet.
Next, set up the first information XMLHttpRequest to mark the contents of the request for the form-encoded. Finally, the form-encoded data as of the request, and send this request. List 3 in a concentrated display of these steps.
Table 3: Send an add to cart XMLHttpRequest
/ * * The product coding, in the shopping cart add an entry * itemCode - need to add entries Product Code * / function addToCart (itemCode) (/ / get a XMLHttpRequest examples newXMLHttpRequest var req = () / / set to receiving requests from the object callback function notice handle var handlerFunction = getReadyStateHandler (req, updateCart); req.onreadystatechange = handlerFunction; / / open a connection to cart the HTTP POST connection servlet / / The third parameter is the request that Asynchronous req.open ( "POST", "cart.do", true); / / instructions of the request form contains data req.setRequestHeader ( "Content-Type", "application / x-www-form-urlencoded") ; / / Send signs need to add to cart in the entry form-encoded data req.send ( "action = add & item =" itemCode);)
With the above, you can understand that Ajax to the first part of the process - the client is to create and send HTTP requests. The next step is to deal with the request of Java Servlet code.
Servlet Request Processing
Through a servlet to handle and deal with a XMLHttpRequest browser from the ordinary HTTP request basically similar. HttpServletRequest.getParameter can call () to obtain from POST request from the form of transmission-encoded data.
Ajax request with the ordinary WEB request of this kind have become the same HttpSession part of the process of conversation. This cart is very Rong example, because we can request the session will be a number of state are kept to the same object JavaBean Cart, and the sequence can be.
Table 4 is dealing with Ajax request and update Cart simple servlet code fragment. Retrieval from the user session in a Cart Bean, in accordance with the parameters of the request to update it.
After Cart Bean to the sequence of XML, and was written to ServletRespone. Attention, it must respond to the content type is set to application / xml, otherwise, would not be able to respond to XMLHttpRequest content analysis as a XML DOM.
Table 4: dealing with the request Ajax code Servlet
Public void doPost (HttpServletRequest req, HttpServletResponse res) throws Java.io.IOException Cart cart = (getCartFromSession (req); String action = req.getParameter ( "action"); String item = req.getParameter ( "item"); if ((action! = null) & & (item! = null)) (/ / shopping cart add or remove an entry if (the "add." equals (action)) (cart.addItem (item);) else if ( "remove." equals (action)) (cart.removeItems (item);)) / / Cart state sequence of the XML String cartXml cart.toXml = () / / XML into the response. res . setContentType ( "application / xml"); res.getWriter (). write (cartXml);)
Table 5 show a Cart.toXml () method generated XML. Noting the cart generated elements of nature, is a through System.currentTimeMillis () generated timestamps.
Table 5: Cart targeted by the sequence of XML
<? Xml version = "1.0"> <cart generated="1123969988414" total="$171.95"> <item code="hat001"> <name> Hat </ name> <quantity> 2 </ quantity> </ item > <item code="cha001"> <name> Chair </ name> <quantity> 1 </ quantity> </ item> <item code="dog001"> <name> Dog </ name> <quantity> 1 < / quantity> </ item> </ cart>
If you look at the download site provides examples of the application source Cart.Java, you will see it by simply additional string to generate XML. For this example, it has been sufficient, I will be in the article, the system introduced after a period of some better ways.
Now that you know how to respond to a CartServlet XMLHttpRequest. The next step is to return to the client, how to respond to the server to update the pages state.
Adopted to deal with the server in response to JavaScript
XMLHttpRequest the readyState property is a request given the state of the life cycle value figures. It has said that "not initialize" 0 change to that "complete" 4. Each readyState change, it will trigger readystatechange, through onreadystatechange attribute configuration callback function will be handling calls.
In Table 3, you have to see getReadyStateHandler by calling the function () function to create a handle, and was configured to onreadystatechange property. GetReadyStateHandler () used to the fact that: JavaScript function is the main target.
This means that the function can be used as parameters to other functions, and you can create and return to other functions. GetReadystateHandler () is to be done is to return to a function to check whether XMLHttpRequet processing has been completed, and deliver XML server response to the call from the designated processing function. List 6 is getReadyStateHandler () code.
List 6: getReadyStateHandler function ()
/ * * Returns a function that waits for the specified XMLHttpRequest * to complete, then passes its XML response to the given handler function. * Req - The XMLHttpRequest whose state is changing * responseXmlHandler - Function to pass the XML response to * / function getReadyStateHandler (req, responseXmlHandler) (/ / return a monitor XMLHttpRequest examples of anonymous functions return function () (/ / If the request is the status of "complete" if (req.readyState == 4) (/ / check whether a server in response to the successful reception if (req.status == 200) (/ / response information will be made available to deal with the XML transfer function responseXmlHandler (req.responseXML);) else (/ / HTTP problems alert ( "HTTP error:" req.status) ;))))
HTTP Status Code
In Table 6, the status XMLHttpRequest attributes to be tested to determine whether the request was completed successfully. When dealing with a simple GET and POST request, you may not think that as long as the 200 (OK), said the state made an error. If the server sends a redirect response (for example, 301 or 302), the browser will redirect transparent and complete access to the new Position of the corresponding resources; XMLHttpRequest redirect state code will not see.
At the same time, the browser automatically add a cache control: for all XMLHttpRequest use no-cache header, this client code can not handle 304 (not-modified) response.
About getReadyStateHandler ()
GetReadyStateHandler () is a relatively complex piece of code, especially when you do not know when to read JavaScript. Compromise JavaScript in your library include this function, you can simply deal with Ajax server response, and not pay attention to XMLHttpRequest spent the internal details. Important is that you have to understand how to use the code getReadyStateHandler ().
In Table 3, you see getReadyStateHandler () call like this:
HandlerFunction = getReadyStateHandler (req, updateCart)
Its return from the function will examine the req variables in the XMLHttpRequest been completed, and call updateCart designated by the callback XML approach to response.
Data Extraction Cart
List 7 showed updateCart () code. Use this function to parse Cart DOM XML documents, and updated WEB pages (see table 1) to reflect the new content of the cart. Attention to the data used to extract the XML DOM calls.
Cart Element generated attributes that to generate the sequence of timestamps, by detecting it can guarantee that the data will not be used to cover old new Cart data. Ajax is asynchronous nature of the request, through the testing process can be effectively avoided, at the server in response to interference.
List 7: update page to reflect the content of XML documents Cart
Function updateCart (cartXML) (/ / get documents from the root element "cart" var cart = cartXML.getElementsByTagName (the "cart") [0]; / / ensure that this document is the latest var generated = cart.getAttribute ( " generated "); if (generated> lastCartUpdate) = (lastCartUpdate generated; / / removals HTML table to display Cart content var contents = document.getElementById (" cart-contents "); contents.innerHTML =" "; / / cart entries by cart.getElementsByTagName cycle var items = ( "item"); for (var I = 0; I <items.length; I) (var item = items [I] / / name Extraction and quantity elements of the text nodes var name = item.getElementsByTagName ( "name") [0]. firstChild.nodeValue; var quantity = item.getElementsByTagName ( "quantity") [0]. firstChild.nodeValue; / / create for entries HTML and add to the list var li = document.createElement ( "li"); li.appendChild (document.createTextNode (name "x" quantity)); contents.appendChild (li);)) / / update Cart the amount of accumulated document.getElementById ( "total"). innerHTML = cart.getAttribute ( "total");)
Now, Ajax process on the end of the tutorial, you may want to use up and running, and how it works. This example is very simple, has great room for improvement. For instance, I included in the server-side code from the shopping cart to remove entry code, but the client did not visit the UI in the way. As an exercise, try on the basis of the existing JavaScript practical this function.
The challenge of the use of Ajax
Like any technology, the use of Ajax in a considerable number of areas may Fan wrong. I am here to discuss the issue of the current lack of solutions, with Ajax and will be resolved or the mature and improve. With Ajax applications development experience in the acquisition, development, the community will be a best practices and guidelines.
The effectiveness of XMLHttpRequest
Ajax developers face the biggest problem is not with the XMLHttpRequest how to react. Although most modern browsers support XMLHttpRequest, but there is still a small number of users, they can not support the browser, or because your browser security settings to prevent the use of XMLHttpRequest.
If your Web application published in the internal Intranet, you are likely to be designated to support either browser, and can ensure that the XMLHttpRequest is available. If you WEB published in the public, you must be aware of the assumption that XMLHttpRequest is available, to stop all the old browser, handheld browser, and so on up to you to use your system.
However, you should try to make sure that applications "normal downgrade" used in the system do not apply to reservations support XMLHttpRequest browser functions. In Cart example, the best way there is a Add to Cart button, can be submitted to the conventional treatment, and refresh page to reflect changes in state Cart.
Ajax line-can be recorded in the pages, through JavaScript added to the page, XMLHttpRequest available only in circumstances for each Add to Cart button with JavaScript handling functions. Another option is to detect when the user login XMLHttpRequest, a decision to provide Ajax-based version or form to the conventional version.
Availability consideration
Ajax applications around most of the problems are very common problems. For example, let users know that their input has been registered and processed, it is very important, because in the process of dealing with XMLHttpRequest can not provide the usual funnel rotation cursor. A method is to "confirm" button on the text replaced with "being updated…", in order to avoid waiting for the response to users repeatedly click of a button.
Another problem is that users may not have noted that they are watching page has been updated. Can be through the use of various visual skills to attract the customer's perspective to the pages of updating the regional. There was also a question by Ajax interrupted pages updated browser "Back" button to work, the URL address bar does not reflect all the pages state, and can not use the bookmark function. See Resource section of the Web site address listed on the article for more on Ajax application usability problems.
Server load
Use Ajax-based interface instead of the traditional form of the interface may be transmitted to the dramatic increase in the number of server requests. For example, an ordinary Google search server to create a hit, and the user when search form. However, Google Suggest, will attempt to automatically complete your search term, users will be unable to send multiple requests to the server.
Ajax in the development of an application, you should note that the number of requests will be sent to end-users, and server load indicators. You can through the appropriate client cache request, and server load mitigation response to the pressure. You should also Ajax application in the design of the client to handle more logic, and not with the server-side communications.
Asynchronous processing
We must remember that there can be no assurance XMLHttpRequest they will be sent in accordance with the order to turn the end. In fact, you in the design of systems, and others should always assume that they will not be the end of the original order. In Cart example, the use of a final update the timestamps to ensure that the latest data will not be rewritten.
This is a very basic approach can Cart scenes work, but it may not work in other cases. In the design of the moment to consider how you deal with asynchronous server response.
Conclusion
You should now to the fundamental principles of Ajax had a good understanding of the other, you should understand some of the more advanced methods come with the Ajax design problems. Create a successful Ajax applications require a wide range of methods - from JavaScript UI design to server architecture - but now you should already have a need to use Ajax to the core knowledge.
- Some of the standards-related web links
- Document.all standards and WEB
- Dreamweaver 8 to get to web standards
- XHTML (WEB standards), I see
- WEB standards: the structure of XHTML tags
- Road to the web standards
- Css & Web standards xhtml
- Xhtml + CSS on the web standards
- Web standards beginner: CSS and XHTML
- WEB standards Frequently Asked Questions
- The commercial value of web standards
- WEB standards establishment - an XHTML Essentials
- Some Thoughts on the web standards
- WEB standards
- Web standards: XHTML + CSS (W3C)
- With hyperlinks to Web standards
- Beginner web standards Misunderstandings
- Web standards for the establishment and its significance
- Web standards, and to where?
- Web standards Beginners: What is XHTML?




