An Introduction To Ajax

转载 2006年05月24日 18:48:00

An Introduction To Ajax

by David Teare


As J2EE developers, it seems we are constantly focused on "backend mechanics." Often, we forget that the main success of J2EE has been around the Web application; people love developing applications that utilize the Web for many reasons, but mainly because the ease of deployment allows a site to have millions of users with minimal cost. Unfortunately, over the years we have invested too much time in the back end and not enough time in making our Web user interfaces natural and responsive to our users.

This article introduces a methodology, Ajax, you can use to build more dynamic and responsive Web applications. The key lies in the combination of browser-side JavaScript, DHTML, and asynchronous communication with the server. This article also demonstrates just how easy it is to start using this approach, by leveraging an Ajax framework (DWR) to construct an application that communicates with backend services directly from the browser. If used properly, this tremendous power allows your application to be more natural and responsive to your users, thereby providing an improved browsing experience.

The sample code used in this application is available for download as a standalone WAR file.


The term Ajax is used to describe a set of technologies that allow browsers to provide users with a more natural browsing experience. Before Ajax, Web sites forced their users into the submit/wait/redisplay paradigm, where the users' actions were always synchronized with the server's "think time." Ajax provides the ability to communicate with the server asynchronously, thereby freeing the user experience from the request/response cycle. With Ajax, when a user clicks a button, you can use JavaScript and DHTML to immediately update the UI, and spawn an asynchronous request to the server to perform an update or query a database. When the request returns, you can then use JavaScript and CSS to update your UI accordingly without refreshing the entire page. Most importantly, users don't even know your code is communicating with the server: the Web site feels like it's instantly responding.

While the infrastructure needed by Ajax has been available for a while, it is only recently that the true power of asynchronous requests has been leveraged. The ability to have an extremely responsive Web site is exciting as it finally allows developers and designers to create "desktop-like" usability with the standard HTML/CSS/JavaScript stack.

Traditionally in J2EE, developers have been so focused on developing the service and persistence layers that the usability of the user interface has lagged behind. It is common to hear phases such as, "we don't have time to invest in the UI" or "you can't do that with HTML" during a typical J2EE development cycle. The following Web sites prove that these excuses don't hold water any longer:

All these Web sites show that Web applications don't need to rely solely on pages being reloaded from the server to present changes to the user. Everything seems to happen almost instantly. In short, when it comes to designing a responsive user interface, the bar has now been set much higher.

Defining Ajax

Jesse James Garrett at Adaptive Path defined Ajax as follows:

Ajax isn't a technology. It's really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:

  1. Standards-based presentation using XHTML and CSS
  2. Dynamic display and interaction using the Document Object Model
  3. Asynchronous server communication using XMLHttpRequest
  4. JavaScript binding everything together

This is all fine and dandy, but why the name Ajax? Well, the term Ajax was coined by Jesse James Garrett, and as he puts it, it is "short-hand for Asynchronous JavaScript + XML."

How Does Ajax Work?

The kernel of Ajax is the XmlHttpRequest JavaScript object. This JavaScript object was originally introduced in Internet Explorer 5, and it is the enabling technology that allows asynchronous requests. In short, XmlHttpRequest lets you use JavaScript to make a request to the server and process the response without blocking the user.

By performing screen updates on the client, you have a great amount of flexibility when it comes to creating your Web site. Here are some ideas for what you can accomplish with Ajax:

  • Dynamically update the totals on your shopping cart without forcing the user to click Update and wait for the server to resend the entire page.
  • Increase site performance by reducing the amount of data downloaded from the server. For example, on Amazon's shopping cart page, when I update the quantity of an item in my basket, the entire page is reloaded, which forces 32K of data to be downloaded. If you use Ajax to calculate the new total, the server can respond with just the new total value, thereby reducing the required bandwidth 100 fold.
  • Eliminate page refreshes every time there is user input. For example, if the user clicks Next on a paginated list, Ajax allows you to just refresh the list with the server data, instead of redrawing the entire page.
  • Edit table data directly in place, without requiring the user to navigate to a new page to edit the data. With Ajax, when the user clicks Edit, you can redraw the static table into a table with editable contents. Once the user clicks Done, you can spawn an Ajax request to update the server, and redraw the table to have static, display-only data.

The possibilities are endless! Hopefully you are excited to get started developing your own Ajax-based site. Before we start, however, let's review an existing Web site that follows the old paradigm of submit/wait/redisplay and discuss how Ajax can improve the user's experience.

Example of Where Ajax Could Be Used: MSN Money

I was on the MSN Money page the other day, and it had an article about real estate investing I found intriguing. I decided to use the "Rate this article" feature of the site such that other users of the site might be encouraged to invest their time in reading the article. After I clicked the vote button and waited a second, the entire page refreshed and I was presented with a beautiful thank you where the original voting question was.

Figure 1
Figure 1. Thank you message

Ajax could have made the user experience more pleasant by providing a more responsive UI and eliminating the flicker of the page refresh. Currently, since the entire page is refreshed, a lot of data needs to be transmitted because the entire page must be resent. If you used Ajax, the server could have sent back a 500-byte message containing the thank you message instead of sending 26,813 bytes to refresh the entire page. Even when using high-speed Internet, the difference between transmitting 26K and 1/2 K is significant! Of equal importance, instead of redrawing the entire screen, only the small section regarding votes would need to be redrawn.

Let's implement our own rudimentary voting system that leverages Ajax.

Raw Ajax: Using the XmlHttpRequest Directly

As alluded to above, the heart of Ajax is the XmlHttpRequest JavaScript object. The following sample article ranking system was built to walk you though the low-level basics of Ajax: Note: If you've already installed the ajax-demo.war in your local WebLogic container, you can navigate to http://localhost:7001/ajax-demo/raw-ajax.html.

Browse the application, cast some votes, and witness firsthand how it behaves. Once you're familiar with the application, continue reading to dig into the details of how it works.

First, you have some simple anchor tags that link to a JavaScript castVote(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 your internal executeXhr function, providing a callback JavaScript function to be executed once the server response is available. Since I need this to run on a simple Apache setup, the "cast vote URL" is just a simple HTML page. In real life, the URL called would tally the votes and dynamically render a response with the vote totals.

The next step is the spawning of an XmlHttpRequest request:

function executeXhr(callback, url) {
  // branch for native XMLHttpRequest object
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
    req.onreadystatechange = callback;"GET", url, true);
  } // branch for IE/Windows ActiveX version
  else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
      req.onreadystatechange = callback;"GET", url, true);

As you can see, executing a XmlHttpRequest is not trivial, but it is straightforward. As always in JavaScript land, the majority of the effort is spent ensuring browser compatibility. In this case, you first determine if the XmlHttpRequest object is available. If it is not, you are likely dealing with Internet Explorer, in which case you  use the ActiveX implementation provided.

The most relevant part of the executeXhr() method is these two lines:

req.onreadystatechange = callback;"GET", url, true);

The first line defines the JavaScript callback function you want to be automatically executed once the response is ready, and the "true" flag specified in the method means you want to execute this request asynchronously.

Once the XmlHttpRequest is processed by the server and returned to the browser, the callback method that you set using the req.onreadystatechange assignment will be automatically invoked:

function processAjaxResponse() {
  // only if req shows "loaded"
  if (req.readyState == 4) {
    // only if "OK"
    if (req.status == 200) {
      $('votes').innerHTML = req.responseText;
    } else {
      alert("There was a problem retrieving the XML data:/n" +

This code is quite terse and uses a few magic numbers, which makes it hard at first to understand what is happening. To clarify this, the following table (borrowed from details the common XmlHttpRequest object properties.

Property Description
onreadystatechange Event handler for an event that fires at every state change
readyState Object status integer:
  1. 0 = uninitialized
  2. 1 = loading
  3. 2 = loaded
  4. 3 = interactive
  5. 4 = complete
responseText String version of data returned from server process
responseXML DOM-compatible document object of data returned from server process
status Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK"
statusText String message accompanying the status code

Now the processVoteResponse() function makes a bit more sense. You first check the overall status of the XmlHttpRequest to ensure it is complete (readyStatus == 4), and then you interrogate the request status as set by the server. If everything is OK (status == 200), you proceed to rewrite the contents of the "votes" node of your DOM by using the innerHTML attribute.

Now that you see firsthand how the XmlHttpRequest object works, let's abstract away the gory details by leveraging a framework built to simplify asynchronous JavaScript communication with Java applications.

Ajax: DWR Style

Following along the same thread of the article rating system, we will implement the same functionality using the Direct Web Remoting (DWR) framework.

Assume that the articles and votes are stored in a database and that you will use some kind of object/relational mapping technique to extract them. To make it as easy as possible to deploy, no database will be used for persistent storage. Furthermore, to keep the application as generic as possible, no Web framework is used either. Instead, the application will start with a static HTML file, which you can assume is rendered dynamically by the server. Despite these simplifying assumptions, your application will use the Spring Framework to tie everything together, thereby making it easy to see how DWR can be leveraged in a "real" application.

Now would be a good time to download the sample application and familiarize yourself with it. The application is bundled as a standard WAR file so you should be able to simply drop it into any Web container—no configuration is needed. Once deployed, browse to http://localhost:7001/ajax_demo/dwr-ajax.html to run the application.

You should view the HTML source code to get an idea of how things work. The most interesting part is how simple the code is—all the interaction with the server is hidden behind the ajaxSampleSvc JavaScript object. What is even more amazing is that the ajaxSampleSvc service was not hand-coded; it was all automatically generated for us! Jump ahead to see how.


Introducing DWR

As demonstrated in the Raw Ajax section, using the XmlHttpRequest directly for creating asynchronous requests is cumbersome. Not only is it verbose in the JavaScript code, you must consider the server-side work needed to route your Ajax requests to the appropriate service, and marshal the result back to the browser.

DWR was invented to handle all the plumbing required to wire up your Web page to your backend services. It is a Java framework you can easily plug into your Web applications to allow your JavaScript code to call services on the server. It even integrates directly with the Spring Framework to allow you to expose your beans directly to the Web client.

What's really neat about DWR is that once you configure the services you want to expose to the client, it uses reflection to generate JavaScript objects that your Web page can use to access your service. Your Web page then simply interfaces with the generated JavaScript objects as if they were using the service directly; DWR seamlessly takes care of all of the dirty details of Ajax and request routing.

Let's dissect our example code to clarify how this works.

Application in Detail: DWR Dissected

The first thing to notice about the application is that it is a standard Java application using the Layered Architecture design pattern. The fact you will use DWR to expose some of your services via JavaScript doesn't affect your design.

Figure 2
Figure 2.

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

package com.tearesolutions.service;

public interface AjaxSampleSvc { 
  Article castVote(int rank);

This is an incredibly simplified example, as you only have one Article that can be voted on. This service is managed by Spring under the bean name ajaxSampleSvc, and depends on the ArticleDao for its persistence needs. See applicationContext.xml for details.

To configure DWR to expose this service as a JavaScript object, you add the dwr.xml file to the WEB-INF directory:

<?xml version="1.0" encoding="UTF-8"?>
 "-//GetAhead Limited//DTD Direct Web Remoting 0.4//EN"
  <create creator="spring" javascript="ajaxSampleSvc">
   <param name="beanName" value="ajaxSampleSvc" />
  <convert converter="bean" match="com.tearesolutions.model.Article"/>
  <exclude method="toString"/>
  <exclude method="setArticleDao"/>

The dwr.xml file tells DWR what services you want to expose directly to your JavaScript code. Notice that you have asked to expose the ajaxSampleSvc Spring bean. DWR will automatically find the Spring ApplicationContext set up by your application. To do this, it requires you to use the standard ContextLoaderListener servlet filter to initialize your Spring ApplicationContext.

DWR is set up as a servlet, and so you add its definition to your web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD 
 Web Application 2.3//EN" "">

 <display-name>Ajax Examples</display-name>


  <display-name>DWR Servlet</display-name>
  <description>Direct Web Remoter Servlet</description>



After this is complete, you can load http://localhost:7001/ajax-demo/dwr to see firsthand what services are available. Doing so shows the following:

Figure 3
Figure 3. The available services

Clicking the ajaxSampleSvc link takes you to a sample implementation of how you could use the service directly within your HTML page. Two included JavaScript files do the majority of the work:

<script type='text/javascript' 
<script type='text/javascript' 

The ajaxSampleSvc.js is generated dynamically:

function ajaxSampleSvc() { }

ajaxSampleSvc.castVote = function(callback, p0)
  DWREngine._execute(callback, '/ajax-demo/dwr', 
 'ajaxSampleSvc', 'castVote', p0);

Now you can go back and refactor your raw-ajax.html file by replacing all the XmlHttpRequest code with this ajaxSampleSvc JavaScript object. The result of this change can be seen in the dwr-ajax.html file; following are the new JavaScript functions:

function castVote(rank) {
  ajaxSampleSvc.castVote(processResponse, rank);
function processResponse(data) {
 var voteText = "<h3>Thanks for Voting!</h3>"
    + "<p>Current ranking: " + data.voteAverage 
    + " out of 5</p>" 
    + "<p>Number of votes placed: " 
    + data.numberOfVotes + "</p>";
 $('votes').innerHTML = voteText;       

Amazingly simple, isn't it? The Article domain object returned by the ajaxSampleSvc object is serialized into a JavaScript object, allowing you to call methods on it such as numberOfVotes() and voteAverage(). You use this data within the HTML code that you dynamically generate and insert into the "votes" DIV element.

Future Work

In a follow-up article, I will extend the conversation on Ajax to include these concepts:

  1. Ajax Best Practices

    Like many technologies, Ajax can be a double-edged sword. There are several use cases where Ajax is overkill for an application and actually hampers usability. I will review some anti-patterns to avoid, highlight some of the negative aspects of Ajax, and show mechanisms to help alleviate them. For example, was Ajax a suitable solution for the Netflix movie browser? Or, how do you cue the user that something really is happening, and clicking the button multiple times will not help?

  2. Managing State Across Requests

    When using Ajax, the document DOM is changed from the original and there's often a lot of page state information that gets stored in client-side variables. When users follow a link to another page in your application, that state is lost. When users inevitably click the Back button, they are presented with the original page from the cache. This can make for very confused users!

  3. Debugging Techniques

    Performing more work on the client side using JavaScript requires some debugging tools to help understand what's going on when things aren't going the way you want.


This article introduced Ajax, and showed how you can use it to create a dynamic and responsive Web application. By using the DWR framework, you can easily incorporate Ajax into your site without worrying about all the mundane plumbing work that must be performed.

Special thanks to Joe Walker and his team at the Getahead IT consultancy for making such a wonderful tool in DWR. Thank you for sharing it with the world!


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


David Teare is a graduate of The University of Western Ontario. He and his wife currently live in the Greater Toronto Area, where their company Teare Software Solutions is based

Introduction to Ajax讲得不错。特别是最后两段,是初学者的苦口良药:思考比c...
  • uoyevoli
  • uoyevoli
  • 2006年06月06日 21:05
  • 1057

abstract 和 introduction的写法

abstract 1. 大背景, 很重要 2.目前问题 3. 考虑到什么因素,提出算法, 解决问题,1-2句 4.pros and cons 5. 实验证明 introdu...
  • seamanj
  • seamanj
  • 2017年01月16日 20:04
  • 663

introduction to Ajax

AJAX  means Asynchronous(异步的) JavaScript and XML. Remember on sentence: It is possible to update pa...
  • ganggang112800
  • ganggang112800
  • 2013年11月22日 10:24
  • 492

Reinforcement Learning:An Introduction 读书笔记- Chapter 1

Reinforcement Learning: An Introduction第一章
  • PeytonPu
  • PeytonPu
  • 2017年11月05日 17:18
  • 83

【读书笔记】《推荐系统(recommender systems An introduction)》第三章 基于内容的推荐

基于内容的推荐的基本推荐思路是:用户喜欢幻想小说,这本书是幻想小说,则用户有可能喜欢这本小说 两方面要求:(1)知道用户的喜好;(2)知道物品的属性 基于内容的推荐相比协同过滤方法(个人观...
  • xceman1997
  • xceman1997
  • 2014年12月07日 21:51
  • 1155

【读书笔记】《推荐系统(recommender systems An introduction)》第一章 引言

很久没上来写blog,前两个月赶上校招季节,都忙校招去了。 这本书我早就买来了,不过我从前看过项亮的《推荐系统实践》,看这本书的目录结构和项亮那本差不多,就一直放着没看。最近在做一个推荐系统...
  • xceman1997
  • xceman1997
  • 2014年12月02日 22:57
  • 1382

An Introduction to GCC

准备工作 注意:本文可能会让你失望,如果你有下列疑问的话:为什么要在终端输命令啊? GCC 是什么东西,怎么在菜单中找不到? GCC 不能有像 VC 那样的窗口吗?…… 那么你真正想要了解的可能...
  • zhangliangaws
  • zhangliangaws
  • 2014年02月23日 21:37
  • 1159

Introduction to Linear Algebra, Fifth Edition.pdf 英文原版 免费下载

下载地址: Introduction to Linear Algebra, Fifth Edition.pdf
  • jiongyi1
  • jiongyi1
  • 2018年01月20日 15:07
  • 764

《reinforcement learning:an introduction》第一章《The Reinforcement Learning Problem》总结

由于组里新同学进来,需要带着他入门RL,选择从silver的课程开始。 对于我自己,增加一个仔细阅读《reinforcement learning:an introduction》的要求。 因为之前读...
  • mmc2015
  • mmc2015
  • 2017年07月10日 17:27
  • 1089

MIT_Introduction to Algorithms课程资料 MIT的算法导论第一节课上,教授就说得了算法的performance的重要性,并非简...
  • winbobob
  • winbobob
  • 2014年06月22日 11:41
  • 1173
您举报文章:An Introduction To Ajax