Introduction to Ajax

Source: Internet
Author: User
Tags add object definition end functions object model string version
Ajax as a Java EE developer, we often seem to focus on the "back-end mechanism (backend mechanics)." We often forget that the main success of Java EE is in Web applications, and many reasons make people like to use web development applications, but primarily because of their ease of deployment, they allow the site to have millions of users at the lowest possible cost. Unfortunately, over the last few years, we've spent too much time on the back end, but not enough to make our Web user interface responsive to the nature and responsiveness of our users.

This article describes a method, Ajax, that you can use to build a more dynamic and responsive Web application. The key to this approach is the combination of JavaScript, DHTML, and asynchronous communication with the server on the browser side. This article also demonstrates how easy it is to enable this method: An AJAX framework (DWR) is used to construct an application that communicates directly from the browser to the backend service. If used properly, this powerful force can make the application more natural and responsive, thereby enhancing the user's browsing experience.

The sample code used in this application has been packaged as a separate war file for download.

Brief introduction

The term Ajax is used to describe a set of techniques that enable browsers to provide a more natural browsing experience for users. Before Ajax, the Web site forced the user into the Submit/wait/display paradigm, and the user's actions were always synchronized with the server's "Think Time." Ajax provides the ability to communicate asynchronously with the server, freeing users from the request/response loop. With Ajax, you can use JavaScript and DHTML to update the UI immediately when the user clicks the button, and to send an asynchronous request to the server to perform an update or query the database. When the request returns, you can use JavaScript and CSS to update the UI appropriately instead of refreshing the entire page. Most importantly, the user doesn't even know that the browser is communicating with the server: The Web site appears to be responding instantly.

While the infrastructure required for Ajax has been on for some time, the true power of the recent asynchronous request has not been exploited. Being able to have a very responsive web site is really exciting because it ultimately allows developers and designers to create "desktop-style (desktop-like)" Usability using standard html/css/javascript stacks.

Typically, in Java EE, developers are too focused on the development of services and persistence layers that the usability of the user interface is lagging behind. In a typical Java EE development cycle, it is often heard that "we have no time to put the UI" or "cannot be implemented in HTML." However, the following Web site proves that these reasons are no longer tenable:

    • BackPack
    • Google suggest
    • Google Maps
    • Palmsphere

All of these Web sites tell us that Web applications do not have to rely entirely on the reload of the page from the server to render changes to the user. Everything seems to happen in an instant. In short, the benchmark is set even higher when it comes to the responsiveness of the user interface.

Defining Ajax

Adaptive Path Company Jesse James Garrett this definition of Ajax:

Ajax is not a technology. In fact, it is a combination of several booming technologies in a new and powerful way. Ajax contains:

    • Representation based on XHTML and CSS standards;
    • Use the document Object model for dynamic display and interaction;
    • Asynchronous communication with the server using XMLHttpRequest;
    • Use JavaScript to bind everything.

This is great, but why do you want to name it Ajax? In fact, the term Ajax was created by Jesse James Garrett, who said it was "shorthand for asynchronous JavaScript + XML."

How Ajax Works

The core of Ajax is the JavaScript object XMLHttpRequest. This object was first introduced in Internet Explorer 5, which is a technology that supports asynchronous requests. In short, XMLHttpRequest allows you to use JavaScript to make requests to the server and process the response without blocking the user.

When you create a Web site, performing a screen update on the client provides a lot of flexibility for the user. Here are the features you can do with Ajax:

    • Dynamically update the total number of items in a shopping cart without requiring the user to click Update and wait for the server to resend the entire page.
    • Improves the performance of the site by reducing the amount of data downloaded from the server. For example, on Amazon's shopping cart page, when the number of items in the basket is updated, the entire page is loaded, which must download 32K of data. If you use Ajax to calculate the new total, the server will only return the new total, so the required bandwidth is only 1%.
    • Eliminates page refreshes each time the user enters. For example, in Ajax, if a user clicks Next on a paging list, the server data refreshes the list instead of the entire page.
    • Edit the table data directly instead of requiring the user to navigate to the new page to edit the data. For Ajax, when a user clicks Edit, the static table can be refreshed to a table that is editable by the content. After the user clicks Done, an AJAX request can be made to update the server and refresh the table so that it contains static, read-only data.

Everything is possible! Hopefully it will inspire you to start developing your own AJAX based sites. Before we begin, however, let's introduce an existing Web site that follows the traditional submission/wait/re-display paradigm, and we'll discuss how Ajax can improve the user experience.

What are the scenarios that Ajax can be used for? --An example: MSN Money page

A few days ago, while browsing the MSN Money page, there was an article about real estate investment that aroused my curiosity. I decided to use the site's "Rate This article" (Evaluate this article) feature to encourage other users to spend a little time reading this article. After I clicked the vote button and waited a little while, the entire page was refreshed, and a beautiful picture of thanks appeared in the original voting question.

Ajax, in turn, can make the user's experience more enjoyable by providing a more responsive UI and eliminating the flicker of page refreshes. Currently, because you want to refresh the entire page, you need to send a large amount of data because you have to resend the entire page. If you use AJAX, the server can return a 500-byte message that contains a thank-you message instead of sending 26,813-byte messages to refresh the entire page. Even with the high-speed Internet, the difference between 26K and 1/2k is very large. It is also important to refresh only the section related to the vote, rather than refreshing the entire screen.

Let's use Ajax to implement our basic voting system.

RAW AJAX: Direct use of XMLHttpRequest

As noted above, the core of Ajax is the JavaScript object XMLHttpRequest. The following example article evaluates the system to take you to the bottom of Ajax basics: http://tearesolutions.com/ajax-demo/raw-ajax.html. Note: If you have Ajax-demo.war installed in the local WebLogic container, you can navigate to http://localhost:7001/ajax-demo/raw-ajax.html.

Browse the application, vote, and see how it works. After you are familiar with the application, read on to learn more about how it works.

First, you have some simple anchor points that are connected to a javascriptcastvote (rank) function.
function Castvote (rank) {  var url = '/ajax-demo/static-article-ranking.html ';  var callback = Processajaxresponse;  EXECUTEXHR (callback, URL);

This function creates a URL for the server resource you want to communicate with and calls the internal function EXECUTEXHR, providing a callback JavaScript function that is executed once the server response is available. Because I want it to run in a simple Apache environment, the cast vote URL is just a simple HTML page. In practice, the URL that is invoked will record the number of votes and dynamically render the response that contains the total number of votes.

The next step is to issue a XMLHttpRequest request:
function executexhr (callback, URL) {  //branch for native XMLHttpRequest object  if (window. XMLHttpRequest) {    req = new XMLHttpRequest ();    Req.onreadystatechange = callback;    Req.open ("Get", url, true);    Req.send (null);  } Branch for Ie/windows ActiveX version  else if (window. ActiveXObject) {    req = new ActiveXObject ("Microsoft.XMLHTTP");    if (req) {      req.onreadystatechange = callback;      Req.open ("Get", url, true);      Req.send ();}}  

As you can see, executing a xmlhttprequest is not simple, but intuitive. As usual, in the field of JavaScript, most of the work is spent on ensuring browser compatibility. In this case, you first need to determine whether XMLHttpRequest is available. If it is not available, you will most likely want to use Internet Explorer, which will use the provided ActiveX implementation.

The most critical part of the EXECUTEXHR () method is the two lines:

Req.onreadystatechange = Callback;req.open ("Get", url, True);

The first line defines the JavaScript callback function, and you want it to execute automatically once the response is ready, and the "true" flag specified in the Req.open () method indicates that you want to execute the request asynchronously.

Once the server has finished processing XMLHttpRequest and returns it to the browser, the callback method that is set by using Req.onreadystatechange assignment is automatically invoked.
function Processajaxresponse () {  //only if Req shows "loaded"  if (req.readystate = 4) {    //only if "OK"    if (Req.status =) {      502 502 ' votes '). InnerHTML = Req.responsetext;    } else {      alert ("There was a problem ret Rieving the XML data: "+      Req.statustext);    }  

The code is fairly concise and uses a few magic numbers, which makes it hard to see what's going on. To figure this out, the following table (referenced from http://developer.apple.com/internet/webcontent/xmlhttpreq.html) enumerates the commonly used XMLHttpRequest object properties.

Property

Describe

onReadyStateChange

Event handlers for events that occur each time the state changes

ReadyState

Object state Value:

  • 0 = uninitialized (uninitialized)
  • 1 = loading (loading)
  • 2 = loading complete (loaded)
  • 3 = interaction (interactive)
  • 4 = complete (complete)

ResponseText

The string form of the data returned from the server process

Responsexml

DOM-compliant document data objects returned from the server process

Status

Numeric code returned from the server, such as 404 (not Found) or 200 (ready)

StatusText

String information for accompanying status codes

Now the Processvoteresponse () function begins to show its meaning. It first checks the overall state of the xmlhttprequest to ensure that it is completed (Readystatus = 4), and then asks for the status of the request based on the server's settings. If everything is ok (status = = 200), use the innerHTML property to override the contents of the DOM's "votes" node.

Now that you've seen how the XMLHttpRequest object works, let's use a framework designed to simplify the asynchronous communication between JavaScript and Java applications to abstract specific details.

Ajax:dwr Way

Following the same process as the article evaluation system, we will implement the same functionality using the direct Web Remoting (DWR) framework.

Assuming that the article and the voting results are stored in a database, an object/relational mapping technique is used to complete the extraction work. In order to be as simple as possible, we do not use a database for persistent storage. In addition, the web framework is not used to make the application as generic as possible. Instead, the application starts with a static HTML file that can be assumed to be dynamically rendered by the server. In addition to these simplifications, applications should use the spring framework to correlate everything so that you can easily see how to use Dwr in a "real" application.

You should now download the sample application and familiarize yourself with it. The application is compressed into a standard war file, so you can put it into any web container-no configuration required. Once the deployment is complete, you can navigate to http://localhost:7001/ajax_demo/dwr-ajax.html to run the program.

You can view the HTML source code and see how it works. The most impressive thing is that the code is so simple-all interactions with the server are hidden behind the JavaScript object ajaxsamplesvc. Even more surprisingly, the AJAXSAMPLESVC service is not written by hand but is automatically generated! Let's go ahead and see how this is done.

Introduction of DWR

As demonstrated in the "Raw Ajax" section, it is cumbersome to create asynchronous requests directly using XMLHttpRequest. Not only is the JavaScript code lengthy, but you must consider the work that the server needs to do to locate the AJAX request to the appropriate service and marshal the results to the browser.

The purpose of the design DWR is to handle all the information pipelines needed to install the Web page to the back-end service. It is a Java framework that can be easily inserted into a Web application so that JavaScript code can invoke services on the server. It even integrates directly with the spring framework, allowing users to expose beans directly to Web clients.

Dwr's real subtlety is that after the user has configured a service to be exposed to the client, it uses reflection to generate JavaScript objects so that Web pages can use them to access the service. The Web page then simply joins the generated JavaScript objects as if they were directly using the service; Dwr seamlessly handles all the trivial details about Ajax and request positioning.

Let's take a closer look at the sample code and figure out how it works.

Application Details: DWR analysis

The first thing to note about the application is that it is a standard Java application that uses a layered architecture (layered architecture) design pattern. Using DWR to expose some services through JavaScript does not affect your design.

Here is a simple Java service that we will use the DWR framework to expose directly to JavaScript code:

Package Com.tearesolutions.service;public interface Ajaxsamplesvc {   Article castvote (int rank);}

This is an example of a simplification to an almost impossible degree, in which only one article can be voted on. The service is managed by spring, and the bean name it uses is Ajaxsamplesvc, and its persistence requirements depend on Articledao. For more information, see Applicationcontext.xml.

In order to expose the service as a JavaScript object, you need to configure DWR and add dwr.xml files to the Web-inf directory:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE dwr Public "-//getahead limited//dtd Direct Web Remoting 0.4//en" "Http://www.getahead.ltd.uk/dwr/dwr.dtd" >& lt;dwr> <allow>  <create creator= "Spring" javascript= "ajaxsamplesvc" >   <param name= " Beanname "value=" Ajaxsamplesvc "/>  </create>  <convert converter=" Bean "match=" Com.tearesolutions.model.Article "/>  <exclude method=" toString "/> <exclude  " Setarticledao "/> </allow></dwr>

The Dwr.xml file tells Dwr which services are to be exposed directly to JavaScript code. Note that the open Spring bean ajaxsamplesvc has been requested. DWR will automatically find the Springapplicationcontext that is set by the application. To do this, you must use the standard servlet filter Contextloaderlistener to initialize the spring ApplicationContext.

DWR is set to a servlet, so add its definition to Web.xml:
<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3. DTD "><web-app> <display-name>ajax examples</display-name> <listener> <listener-class > Org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <servlet&  Gt <servlet-name>ajax_sample</servlet-name> <servlet-class> Com.tearesolutions.web.ajaxsampleservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>dwr-invoker</servlet-name> <display-name>dwr servlet</display-name> <description>direct Web remoter servlet</description> <servlet-class >uk.ltd.getahead.dwr.DWRServlet</servlet-class> <init-param> <param-name>debug</ Param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ajax_sample</servlet-name> < url-pattern>/ajax_sample</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name >dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping></ Web-app>

After you have done this, you can load the HTTP://LOCALHOST:7001/AJAX-DEMO/DWR to see which services are available. The results are as follows:

Figure 3. Available services

Click the ajaxsamplesvc link to see an example implementation of how to use the service directly within an HTML page. It contains two JavaScript files that perform most of the functions:
<script type= ' text/javascript '    src= '/ajax-demo/dwr/interface/ajaxsamplesvc.js ' ></script>< Script type= ' text/javascript '    src= '/ajax-demo/dwr/engine.js ' ></script>

Ajaxsamplesvc.js are dynamically generated:

function Ajaxsamplesvc () {}ajaxsamplesvc.castvote = function (callback, p0) {   Dwrengine._execute (callback, '/ Ajax-demo/dwr ',  ' ajaxsamplesvc ', ' castvote ', p0);

You can now refactor raw-ajax.html files by replacing all XMLHttpRequest code with JavaScript object ajaxsamplesvc. You can see the results of the changes in the dwr-ajax.html file, and the following are the new JavaScript functions:

function Castvote (rank) {  ajaxsamplesvc.castvote (processresponse, rank);} function ProcessResponse (data) {var votetext = "

For voting!

" + "

Current ranking: "+ data.voteaverage +" out of 5

" + "

Number of votes placed: " + data.numberofvotes +"

"; 502 502 ' votes '). InnerHTML = Votetext; }

Amazingly simple, isn't it? The article domain object returned by the Ajaxsamplesvc object is serialized as a JavaScript object, allowing methods such as numberofvotes () and Voteaverage () to be invoked above it. Use this data within the HTML code that is dynamically generated and inserted into the div element "votes".

Next work

In subsequent articles, I will continue with the topic of Ajax, which covers the following areas:

    • Ajax Best Practices

Like many technologies, Ajax is a double-edged sword. For some use cases, there is no need to use Ajax for their applications, which in turn is detrimental to usability. I'll introduce some patterns that aren't appropriate, highlight some of the negative aspects of Ajax, and show some of the mechanisms that help mitigate these negative aspects. For example, is Ajax the right solution for Netflix movie browsers? Or, how do you prompt the user for some problems and click the button again?

    • Managing cross-Request status

When using AJAX, the original document DOM changes, and a large amount of page state information is stored in the client variable. When a user tracks a link to another page in the application, the status is lost. When users click the Back button as usual, the initial page in the cache is presented to them. This will make users feel very confused!

    • Debugging Tips

When you use JavaScript to do more work on the client, if things don't go as expected, you need some debugging tools to help you figure out what's wrong.

Conclusion

This article describes the AJAX approach and shows how to use it to create a dynamic and responsive Web application. By using the DWR framework, you can easily integrate Ajax into your site without worrying about all the actual plumbing work that must be done.

Special thanks to Joe Walker of Getahead IT consulting and his team for developing such a magical tool as DWR. Thank you for sharing it with the world!

Download

The application source code that is demonstrated in this article is available for download: Ajax-demo.war (1.52 MB).

Resources

    • Http://www.getahead.ltd.uk/dwr--Getahead IT consulting firm.
    • "Ajax:a New approach to Web applications" written by Jesse James Garrett (Adaptive path,2005 year February).
    • "Dynamic HTML and Xml:the xmlhttprequest Object" (Apple Developer Connection).

Original source

An Introduction to Ajax

Http://dev2dev.bea.com/pub/a/2005/08/ajax_introduction.html



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.