How to Learn Ajax technology

Source: Internet
Author: User

As a J2EE developer, we often seem to be concerned with backend mechanisms )". We often forget that the main success of J2EE lies in Web applications. Many reasons make people prefer to use web to develop applications, however, it is mainly because of its ease of deployment that allows websites to own millions of users at the lowest possible cost. Unfortunately, over the past few years, we have invested too much time at the backend, but we have not invested enough in making our web user interfaces more responsive and natural to users.

This article introduces a method called Ajax that can be used to build more dynamic and responsive web applications. The key of this method is the combination of JavaScript, DHTML, and asynchronous communication with the server. This article also demonstrates how easy it is to enable this method: using an Ajax framework (DWR) to construct an application that communicates directly with the backend service from the browser. If used properly, this powerful force can make the application more natural and responsive, thus improving the user's browsing experience.

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

Introduction

The term Ajax is used to describe a group of technologies that allow browsers to provide users with a more natural browsing experience. Before Ajax, the Web site forces the user to enter the submit/Wait/re-display example, and the user's actions are always synchronized with the "thinking time" of the server. Ajax provides the ability to communicate asynchronously with the server, freeing users from the loop of requests/responses. With Ajax, you can use JavaScript and DHTML to immediately update the UI when you click a button, and send an asynchronous request to the server for updating or querying the database. When a request is returned, you can use JavaScript and CSS to update the UI, instead of refreshing the entire page. Most importantly, users do not even know that the browser is communicating with the server: The Web site seems to be responding instantly.

Although the infrastructure required by Ajax has been around for a while, the real power of asynchronous requests has not been exploited until recently. It is really exciting to have a very responsive web site, it eventually allows developers and designers to use standard HTML, CSS, and JavaScript stacks to create "desktop-like" availability.

Usually, in J2EE, developers focus too much on service and persistence layer development, so that the availability of user interfaces has lagged behind. In a typical J2EE development cycle, we often hear this: "We have no time to invest in the UI" or "HTML cannot be used for implementation ". However, the following web sites prove that these reasons are no longer justified:

Backpack
Google suggest
Google Maps
Palmsphere
All these web sites tell us that Web applications do not have to rely entirely on re-loading pages from servers to present changes to users. Everything seems to happen in an instant. In short, when the response sensitivity of the user interface is involved, the benchmark is set higher.

Define Ajax

Jesse James Garnett of Adaptive Path defines Ajax as follows:

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

Representation Based on XHTML and CSS standards;
Use Document Object Model for Dynamic Display and interaction;
Use XMLHttpRequest for asynchronous communication with the server;
Use JavaScript to bind everything.
This is very good, but why is it named after Ajax? In fact, the term Ajax was created by Jesse James Garnett, who said it was "Asynchronous JavaScript + XML shorthand ".

How Ajax works

The core of AJAX is the JavaScript Object XMLHttpRequest. This object was first introduced in Internet Explorer 5. It is a technology that supports asynchronous requests. In short, XMLHttpRequest allows you to use JavaScript to request and process responses to the server without blocking users.

When creating a web site, executing screen updates on the client gives you great flexibility. The following functions can be completed using Ajax:

Dynamically update the total number of items in the shopping cart. You do not need to click Update and wait for the server to resend the entire page.
This improves site performance by reducing the amount of data downloaded from the server. For example, on the Amazon shopping cart page, when updating the number of items in the basket, the entire page is reloaded, which must download 32 K data. If Ajax is used to calculate the new total, the server returns only the new total value, so the required bandwidth is only 1% of the original total.
This eliminates the page refresh for each user input. For example, in Ajax, if you click Next on the page list, the server data will only refresh the list rather than the whole page.
Directly edit table data, rather than requiring users to navigate to a new page to edit data. For Ajax, When you click Edit, You can refresh the static table as an editable table. After you Click Done, you can send an Ajax request to update the server and refresh the table so that it contains static and read-only data.
Everything is possible! Hopefully it will inspire you to start developing your own Ajax-based site. However, before getting started, let's introduce an existing web site that follows the traditional example of submitting, waiting, and re-displaying. We will also discuss how Ajax improves user experience.

Which scenarios can Ajax be used in? -- Example: MSN Money page

A few days ago, when I browsed the MSN Money page, an article about real estate investment aroused my curiosity. I decided to use the site's "rate this article" feature to encourage other users to spend a little time reading this article. After I clicked the vote button and waited for a while, the entire page was refreshed, and a beautiful Thank-You screen was displayed in the original voting place.

 

While AJAX can make the user experience more pleasant, it can provide a more responsive UI, and eliminate the flickering caused by PAGE refreshing. Currently, to refresh the entire page, you need to transmit a large amount of data because you must resend the entire page. If Ajax is used, the server can return a 500-byte message containing the thanks message, instead of sending a 26,813-byte message to refresh the entire page. Even if you are using a high-speed Internet, the difference between transmission of 26 K and 1/2 k is also very large. Similarly, you only need to refresh the voting-related section, rather than refresh the entire screen.

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

Original Ajax: Use XMLHttpRequest directly

As mentioned above, the core of AJAX is the JavaScript Object XMLHttpRequest. In the following example, the evaluation system will familiarize you with the basic knowledge of Ajax: http://tearesolutions.com/ajax-demo/raw-ajax.html. Note: If you have installed a ajax-demo.war in your local WebLogic container, you can navigate to http: // localhost: 7001/Ajax-demo/raw-ajax.html,

Browse the application, participate in the voting, and see with your own eyes how it works. After familiarizing yourself with the application, continue reading and learn more about its working principles.

First, you have some simple positioning 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 );
}
The worker function creates a URL for the server resource to communicate with and calls the executexhr internal function. It provides a callback JavaScript function. Once the server response is available, the function is executed. Because I want it to run in a simple Apache environment, "cast vote URL" is just a simple HTML page. In actual situations, the called URL records the number of votes and dynamically displays the response containing the total number of votes.

The next step is to send an 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 an XMLHttpRequest is not simple, but intuitive. As usual, in the Javascript field, most of the work is spent on ensuring browser compatibility. In this case, you must first determine whether XMLHttpRequest is available. If it cannot be used, it is likely to use Internet Explorer, so you must use the provided ActiveX implementation.

The most important part of the executexhr () method is the two rows:

Req. onreadystatechange = callback;
Req. Open ("get", URL, true );
The first line defines the Javascript callback function, and you want it to be automatically executed once the response is ready, and req. the "true" flag specified in the open () method indicates that you want to execute the request asynchronously.

Once the server completes XMLHttpRequest processing and returns it to the browser, the callback method assigned by Req. onreadystatechange is automatically called.
Function processajaxresponse (){
// Only if req shows "loaded"
If (req. readystate = 4 ){
// Only if "OK"
If (req. Status = 200 ){
502 502 'votes '). innerhtml = Req. responsetext;
} Else {
Alert ("there was a problem retrieving the XML data:
"+
Req. statustext );
}
}
}
The code is quite concise and uses several magic numbers, which makes it difficult to see what happened at once. To clarify this, the following table (referencing from the http://developer.apple.com/internet/webcontent/xmlhttpreq.html) lists the commonly used XMLHTTPRequest object attributes.

Attribute
Description

Onreadystatechange
Event handler for the event triggered by each state change

Readystate
Object status value:

0 = uninitialized)
1 = Loading)
2 = loaded)
3 = interactive)
4 = complete)

Responsetext
String format of the data returned from the server process

Responsexml
Dom-compatible document data objects returned from server processes

Status
Number Code returned from the server, such as 404 (not found) or 200 (ready)

Statustext
String information of the accompanied status code

Now the processvoteresponse () function is showing its meaning. It first checks the overall status of XMLHttpRequest to ensure that it has been completed (readystatus = 4), and then queries the Request status based on the server settings. If everything is normal (status = 200), use the innerhtml attribute to overwrite the content of the DOM "votes" node.

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

Ajax: DWR Mode

Following the same process as the article evaluation system, we will use the direct Web remoting (DWR) framework to implement the same functions.

Assume that the article and voting results are stored in a database, and some object/relationship ing technology is used for extraction. To make the deployment as simple as possible, we do not use databases for persistent storage. In addition, in order to make the application as common as possible, the Web framework is not used. On the contrary, an application starts from a static html file and can be considered to be dynamically rendered by the server. In addition to these simplified measures, applications should also use Spring framework to associate everything so that they can easily see how to use DWR in a "real" application.

Download the sample application and familiarize yourself with it. This application is compressed into a standard war file, so you can place it in any Web Container-No configuration required. After 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 to learn 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. What's even more surprising is that the ajaxsamplesvc service is not manually written but completely automatically generated! Let's continue and see how this works.

Introduce DWR

As demonstrated in the "original Ajax" section, using XMLHttpRequest to create asynchronous requests is very troublesome. Not only is JavaScript code lengthy, but the server must consider the work required to locate Ajax requests to the appropriate service and mail the results to the browser.

DWR is designed to process all the information pipelines required to install Web pages on backend services. It is a Java framework that can be easily inserted into Web applications so that JavaScript code can call services on the server. It is even directly integrated with Spring framework, allowing users to directly publish beans to web clients.

DWR uses reflection to generate JavaScript objects after a user configures a service to be made public to the client, so that web pages can use these objects to access the service. Then the web page only needs to join the generated JavaScript objects, just as they are directly using the service; DWR seamlessly handles all the trivial details about Ajax and request locating.

Let's analyze the sample code carefully to find out how it works.

Application details: DWR Analysis

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

 

The following is a simple Java service. We will use the DWR framework to publish it directly to JavaScript code:

Package com. tearesolutions. Service;

Public interface ajaxsamplesvc {
Article castvote (INT rank );
}
This is an example that is simplified to an almost impossible level. Only one article can vote. The service is managed by spring, and the bean name used is ajaxsamplesvc. Its persistence requirement depends on articledao. For more information, see applicationcontext. xml.

To expose the service as a JavaScript Object, You need to configure DWR and add the DWR. xml file 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>

<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 method = "setarticledao"/>
</Allow>
</DWR>
The DWR. xml file tells DWR which services should be made public directly to JavaScript code. Note that spring bean ajaxsamplesvc has been required to be published. DWR will automatically find the springapplicationcontext set by the application. Therefore, you must use the standard servlet filter contextloaderlistener to initialize spring applicationcontext.

DWR is set as 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>
<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 completing these steps, you can load http: // localhost: 7001/Ajax-demo/DWR to see which services are available. The result is as follows:

 

Figure 3. Available Services

Click the ajaxsamplesvc link to view how to directly use the service sample on the HTML page. The two JavaScript files are used to complete 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 is dynamically generated:

Function ajaxsamplesvc (){}

Ajaxsamplesvc. castvote = function (callback, P0)
{
Dwrengine. _ execute (callback, '/Ajax-demo/dwr ',
'Ajaxsamplesvc', 'castvote', P0 );
}
Now, you can use the javascriptobject ajaxsamplesvcto replace all xmlhttprequestcodes and recreate the raw-ajax.html file. You can see the change result in the dwr-ajax.html file. The following is a new JavaScript function:

Function castvote (rank ){
Ajaxsamplesvc. castvote (processresponse, rank );
}
Function processresponse (data ){
VaR votetext = "Thanks for voting! "
+ "Current ranking:" + data. voteaverage
+ "Out of 5"
+ "Number of votes placed :"
+ Data. numberofvotes + "";
502 502 'votes '). innerhtml = votetext;
}
Surprisingly simple, isn't it? The article domain object returned by the ajaxsamplesvc object is serialized as a JavaScript Object that allows you to call methods such as numberofvotes () and voteaverage () on it. Use the data in the HTML code dynamically generated and inserted into the DIV element "votes.

Next step

In subsequent articles, I will continue to discuss Ajax, covering the following aspects:

Ajax Best Practices
Like many technologies, Ajax is a double-edged sword. For some use cases, it is not necessary for their applications to use Ajax, but the availability is lossy. I will introduce some unsuitable patterns, highlight some negative aspects of Ajax, and demonstrate some mechanisms that help ease these negative aspects. For example, Is Ajax a suitable solution for Netflix movie browsers? Or, how do I prompt the user that something is wrong, and clicking the button again does not help?

Manage cross-request statuses
When Ajax is used, the initial document Dom changes and a large amount of page status information is stored in client variables. When a user traces a link to another page in the application, the status is lost. When you click the back button as usual, the initial page in the cache is displayed to them. This will confuse users!

Debugging skills
When Javascript is used to execute more work on the client, if things are not performed as expected, some debugging tools are needed to help identify the problem.

Conclusion

This document introduces the Ajax method and shows how to use it to create a dynamic and responsive web application. By using the DWR framework, AJAX can be easily integrated into the site without worrying about all the actual pipeline work that must be performed.

Special thanks to Joe Walker of getahead IT Consulting and his team for developing magic tools such as DWR. Thank you for sharing it with the world!

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.