Get started with Ajax-Part 2: getting started with Ajax-from IBM-developerworks

Source: Internet
Author: User
Tags response code
Get started with Ajax, Part 1: Ajax Introduction

An effective method to build websites by understanding Ajax and its working principles

Brett McLaughlin (, author, editor, O 'Reilly Media Inc.


Introduction:Ajax is composed of HTML, JavaScript technology, DHTML, and Dom. This outstanding method can convert clumsy web interfaces into interactive Ajax applications. The author of this series is an Ajax expert who demonstrates how these technologies work collaboratively-from an overview to a detailed discussion-to make efficient web development a reality. He also unveiled the secrets of Ajax core concepts, including XMLHttpRequest objects.

Five years ago, if you do not know XML, you are an ugly duckling that no one cares about. Eighteen months ago, Ruby became the focus of attention. programmers who did not know Ruby had to sit on the bench. Today, if you want to keep up with the latest technology, your goal is Ajax.

However, Ajax does notOnlyIt is a fashion. It is a powerful way to build websites, and it is not as difficult as learning a brand new language.

Visit the Ajax technical resource center, an all-in-one center for Ajax programming model information, including many documents, tutorials, forums, blogs, wikis, and news. Any new information can be found here.

But before discussing in detail what Ajax is, let's take a few minutes to understand Ajax.DoWhat. Currently, there are two basic options for compiling an application:

  • Desktop applications
  • Web Applications

The two are similar. desktop applications usually use CD as the media (sometimes download from a website) and are fully installed on your computer. Desktop applications may download updates over the Internet, but the code for running these applications is on the desktop computer. Web applications run on a Web server somewhere-it's no surprise that you need to access such applications through a web browser.

However, what is more important than where the Running code of these applications is, how the applications run and how they interact with them. Desktop applications are usually very fast (running on your computer without waiting for Internet connections), with beautiful user interfaces (usually related to the operating system) and extraordinary dynamics. You can click, select, enter, open menus, submenus, and parade around, basically without waiting.

On the other hand, web applications are the latest trend, providing services that cannot be implemented on the desktop (such as and eBay ). However, as the Web is powerful, it appears to wait for the server to respond, wait for the screen to refresh, wait for the request to return and generate a new page.

Obviously, this is simple, but this is the basic concept. As you may have guessed, Ajax tries to build a bridge between the functions and interactivity of desktop applications and constantly updated web applications. You can use dynamic user interfaces and beautiful controls that are common in desktop applications, but in Web applications.

What are you waiting? Let's take a look at how Ajax converts a clumsy web interface into a responsive Ajax application.

Old technology and new skills

When talking about Ajax, there are actually multiple technologies involved. To use it flexibly, you must gain an in-depth understanding of these different technologies (the first few articles in this series will discuss these technologies separately ). The good news is that you may already be very familiar with most of these technologies. Even better, these technologies are easy to learn and not as difficult as a complete programming language (such as Java or Ruby.

Ajax Definition

By the way, Ajax is short for Asynchronous JavaScript and XML (and DHTML. This phrase was invented by Jesse James Garnett of Adaptive Path (see references). According to Jesse's explanationNoAcronyms.

The following are the basic technologies used by Ajax applications:

  • HTML is used to create a web form and determine the fields used by other parts of the application.
  • JavaScript code is the core code for running Ajax applications and helps improve communication with server applications.
  • DHTML or dynamic HTML, used to dynamically update forms. We will usediv,spanAnd other dynamic HTML elements to mark HTML.
  • The Document Object Model Dom is used to process HTML structures (using JavaScript code) and (in some cases) the XML returned by the server.

Let's further analyze the responsibilities of these technologies. In future articles, I will discuss these technologies in depth. Now I only need to be familiar with these components and technologies. The more familiar the code, the easier it will be to shift from a fragmented understanding of these technologies to a true grasp of these technologies (and truly open the door to Web Application Development ).

XMLHTTPRequest object

An object You Want To Know may be the most unfamiliar to you, that isXMLHttpRequest. This is a JavaScript Object. It is easy to create this object, as shown in Listing 1.

Listing 1. Creating a New XMLHTTPRequest object

<script language="javascript" type="text/javascript">
  var xmlHttp = new XMLHttpRequest();


This object will be further discussed in the next article. Now you need to know that this is the object for processing all server communications. Before continuing reading, stop and think about it: PassXMLHttpRequestWhat is the conversation between the object and the server?JavascriptTechnology. This is not a general application stream, but a source of powerful Ajax functions.

In a common web application, enter the form field and clickSubmitButton. Then the entire form is sent to the server, and the server forwards it to the script that processes the form (usually PHP or Java, or CGI process or something similar ), after the script is executed, send it back to the new page. This page may contain html of a new form with some data filled, a confirmation page, or a page with certain options selected based on the input data in the original form. Of course, the user must wait when the script or program on the server processes and returns a new form. The screen becomes blank and will be re-drawn after the server returns data. This is the cause of poor interaction. users do not receive immediate feedback, so they feel different from desktop applications.

In Ajax, JavaScript andXMLHttpRequestPut objects on web forms and serversBetween. When the user fills out the form, the data is sent to some JavaScript code whileNoDirectly sent to the server. On the contrary, JavaScript code captures form data and sends requests to the server. At the same time, forms on the user's screen do not flash, disappear, or delay. In other words, JavaScript code sends a request behind the scenes, and the user does not even know how to send the request. Even better, requests are sent asynchronously, that is, JavaScript code (and users) does not have to wait for the response from the server. Therefore, you can continue to input data, scroll the screen, and use applications.

The server then returns the data to the JavaScript code (still in the web form), which decides how to process the data. It can quickly update the form data, making users feel that the application is completed immediately, the form is not submitted or refreshed, and users get new data. JavaScript code can even execute some calculation on the received data and send another request without user intervention! This isXMLHttpRequest. It can interact with the server as needed, and the user may not even know what happened behind the scenes. The result is similar to the dynamic, rapid response, and highly interactive experience of desktop applications, but it has all the power of the Internet.

Add some Javascript

GetXMLHttpRequestOther JavaScript code is very simple. In fact, we will use JavaScript code to complete very basic tasks:

  • Get form data: JavaScript code can easily extract data from HTML forms and send it to the server.
  • Modify the data on the form: Updating the form is also very easy, from setting the field value to quickly replacing the image.
  • Parse HTML and XML: use JavaScript code to manipulate the DOM (see the next section) and process the XML Data Structure returned by the HTML form server.

Be familiar with the first two pointsgetElementById()Method, as shown in Listing 2.

Listing 2. Capturing and setting field values with JavaScript code

Get the value of the "phone" field and stuff it in a variable called phone
  var phone = document.getElementById("phone").value;
// Set some values on a form using an array called response
document.getElementById("order").value = response[0];
document.getElementById("address").value = response[1];


There is nothing special to note here. It's really great! You should realize that there is nothing very complicated here. As long as you have masteredXMLHttpRequestThe other part of the Ajax application is the simple JavaScript code shown in Listing 2, with a small amount of HTML mixed. At the same time, we need to use a little Dom. Let's take a look.

End with Dom

There is also the Dom, that is, the Document Object Model. Dom may be a little daunting for some readers. html designers seldom use it, even JavaScript programmers do not use it unless they want to complete a high-end programming task. A large number of DOMYesComplex Java and C/C ++ programs, which may be the reason why Dom is considered hard to learn.

Fortunately, it is easy and intuitive to use DOM in javascript technology. Now, you may need to explain how to use Dom, or at least give some sample code, but this may mislead you. Even if I ignore Dom, I can still explore Ajax in depth, which is also the method I want to adopt. In future articles, we will discuss Dom again. Now we only need to know that Dom is required. When we need to pass XML and change HTML forms between JavaScript code and the server, we will study DOM in depth. You can do some interesting work without it, so now let's put the DOM aside.

GET request object

With the basic knowledge above, let's take a look at some specific examples.XMLHttpRequestIt is the core of Ajax applications and may be unfamiliar to many readers. Let's start from here. From list 1, we can see that creating and using this object is very simple, isn't it? Wait.

Do you still remember the nasty Browser Wars a few years ago? Nothing returns the same result on different browsers. Whether you believe it or not, these wars are still going on, although the scale is small. But what's strange is that,XMLHttpRequestIt became one of the victims of the war. ThereforeXMLHttpRequestObjects may need different methods. I will explain it in detail below.

Use the Microsoft browser

Microsoft browser Internet Explorer uses the MSXML parser to process XML (for more information about MSXML, see references ). Therefore, if an Ajax application needs to work with Internet Explorer, an object must be created in a special way.

But it is not that simple. Depending on the version of JavaScript technology installed in Internet Explorer, MSXML actually has two different versions. Therefore, you must write code for these two cases. See listing 3. The Code createsXMLHttpRequest.

Listing 3. Create an XMLHTTPRequest object in the Microsoft browser

var xmlHttp = false;
try {  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");} 
catch (e) {  try {    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  } 
catch (e2) {    xmlHttp = false;  }}


You may not fully understand the code, but it does not matter. At the end of this series of articles, you will have a better understanding of JavaScript programming, error handling, and Conditional compilation. Now you only need to remember the two lines of code:

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");


xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");.

These two lines of code basically try to create an object using a version of MSXML. If the Code fails, use another version to create the object. Good, right? If none of them are successfulxmlHttpSet the variable to false to indicate that the code is faulty. If this happens, it may be because a non-Microsoft browser is installed and different code is required.

Processing Mozilla and non-Microsoft browsers

If the selected browser is not Internet Explorer, or you want to write code for a non-Microsoft browser, you need to use different codes. In fact, it is a simple line of code shown in Listing 1:

var xmlHttp = new XMLHttpRequest object;.

This line of much simpler code is created in Mozilla, Firefox, Safari, opera, and basically all non-Microsoft browsers that support Ajax in any form or method.XMLHttpRequestObject.


The key is to supportAllBrowser. Who wants to write an application that can only be used in Internet Explorer or non-Microsoft browsers? Or worse, write an application twice? Of course not! Therefore, the Code must support both Internet Explorer and non-Microsoft browsers. Listing 4 shows the code.

Listing 4. Creating XMLHttpRequest objects in multiple browsers

/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");} 
catch (e) {  try {    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");  }
 catch (e2) {    xmlHttp = false;  }}
@end @*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') 
{  xmlHttp = new XMLHttpRequest();}


Now let's ignore the strange symbols that have been commented out, such@cc_onThis is a special JavaScript compiler command.XMLHttpRequest. The core of this Code is divided into three steps:

  1. Create a variablexmlHttpTo referenceXMLHttpRequestObject.
  2. Try to create this object in Microsoft browser:
    • Try to useMsxml2.XMLHTTPObject.
    • If it fails, try againMicrosoft.XMLHTTPObject.
  3. If noxmlHttp, The object is created in a non-Microsoft manner.

Finally,xmlHttpA validXMLHttpRequestRegardless of the browser.


How is security? Now the Browser allows users to increase their security levels, disable javascript technology, and disable any options in the browser. In this case, the Code does not work anyway. At this time, the problem must be properly handled. This should be discussed in a separate article. It should be put into the future (is this series long enough? Don't worry, you may have mastered it before reading it ). Now we need to write a robust but not perfect code, which is good for mastering Ajax. We will discuss more details later.

Requests/responses in the Ajax world

Now we have introduced AjaxXMLHttpRequestObject and how to create it. If you read it carefully, you may already know that the Web application on the server is dealing with JavaScript technology, rather than submitting HTML forms directly to that application.

What is missing? How to UseXMLHttpRequest. Because this code is very importantEachAjax applications must use it in some form. Let's first look at the basic request/Response Model of Ajax.

Send request

You have a brand newXMLHttpRequestObject. Now let it do some work. First, you need a JavaScript method that can be called on a web page (for example, when a user inputs text or selects an item from the menu ). The next step is basically the same process in all Ajax applications:

  1. Obtain the required data from the web form.
  2. Create the URL to be connected.
  3. Open the connection to the server.
  4. Set the function to run after the server is complete.
  5. Send a request.

The example Ajax method in listing 5 is organized in this order:

Listing 5. Sending Ajax requests

function callServer() 
{  // Get the city and state from the web form  
var city = document.getElementById("city").value; 
 var state = document.getElementById("state").value; 
 // Only go on if there are values for both fields
  if ((city == null) || (city == "")) return; 
 if ((state == null) || (state == "")) return; 
 // Build the URL to connect to
  var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state); 
 // Open a connection to the server"GET", url, true); 
 // Setup a function for the server to run when it's done
  xmlHttp.onreadystatechange = updatePage;
  // Send the request


Most of the Code has clear meanings. The initial code uses the basic JavaScript code to obtain the values of several form fields. Set a PHP script as the link target. Pay attention to the method specified by the Script URL. City and State (from the form) are appended after the URL with a simple get parameter.

Then open a connection. This is the first time you seeXMLHttpRequest. The connection method (get) and the URL to be connected are specified. If the last parameter is settrue, Then an asynchronous connection will be requested (this is the origin of Ajax ). If you usefalseAfter the code sends a request, it will wait for the response returned by the server. IftrueWhen the server processes requests in the background, users can still use forms (or even call other Javascript methods ).

xmlHttp(Remember, this isXMLHttpRequestObject instance)onreadystatechangeThe attribute can tell the server that it is runningCompleteAfter (may take five minutes or five hours. Because the Code does not wait for the server, you must let the server know how to do so that you can respond. In this example, if the server has processed the request, a specialupdatePage()Will be triggered.

Finally, use the valuenullCallsend(). Because the data (city and state) to be sent to the server has been added to the request URL, no data needs to be sent in the request. In this way, a request is sent, and the server works according to your requirements.

If you haven't found anything new, you should realize how simple and clear it is! In addition to keeping in mind the asynchronous features of Ajax, these contents are quite simple. Thanks to Ajax, you can focus on writing beautiful applications and interfaces without worrying about complicated HTTP Request/response code.

The code in listing 5 illustrates the ease of use of Ajax. Data is a simple text that can be used as part of the request URL. Use get instead of more complex post to send requests. There is no XML and Content Header to be added, and there is no data to be sent in the Request body; in other words, this is the utopia of Ajax.

Don't worry. As this series of articles expands, things will become more and more complex. You will see how to send post requests, how to set request headers and content types, how to encode XML in messages, and how to increase request security. There are still a lot to do! For the time being, you don't have to worry about the difficulties. Just master the basic things. Soon we will build a complete set of Ajax Tool libraries.

Handling response

Now we have to respond to the server. Now you only need to know two points:

  • Do nothingxmlHttp.readyStateThe property value is 4.
  • The server will fill in the responsexmlHttp.responseTextAttribute.

The first point, the readiness status, will be discussed in detail in the next article. You will learn more about the HTTP request stage, probably more than you have imagined. Now you only need to check a specific value (4) (more values will be introduced in the next article ). Second, usexmlHttp.responseTextAttribute to obtain the server response, which is very simple. The sample method in Listing 6 can be called by the server based on the data sent in listing 5.

Listing 6. Handling server responses

function updatePage() 
 if (xmlHttp.readyState == 4) 
  {    var response = xmlHttp.responseText;  
      document.getElementById("zipCode").value = response; 

The code is neither difficult nor complex. It is waiting for the server to call. If it is in the ready state, use the value returned by the server (here is the zip code of the City and State entered by the user) to set the value of another form field. So it contains the zip codezipCodeThe field suddenly appears, and the userNo button is pressed! This is the feeling of desktop applications. Fast response, dynamic feelings, and so on, all of which are due to a small piece of Ajax code.

Careful readers may noticezipCodeIs a common text field. Once the server returns the zip code,updatePage()The method uses the zip code of the city/State to set the value of that field, and the user can rewrite this value. There are two reasons for doing this: Keep the example simple, and sometimes it is possibleHopeThe user can modify the data returned by the server. Remember these two points. They are important for good user interface design.


Connect to Web Forms

What else? Actually not much. One JavaScript method captures the information of the user input form and sends it to the server. The other JavaScript method listens to and processes the response, and sets the field value when the response is returned. All of these actually depend onCallThe first JavaScript method starts the entire process. The most obvious way is to add a button in the HTML form, but this is the 2001 method. Do you think so? Use JavaScript technology like listing 7.

Listing 7. Start an Ajax Process

 <p>City: <input type="text" name="city" id="city" size="25" onChange="callServer();" /></p> 
 <p>State: <input type="text" name="state" id="state" size="25" onChange="callServer();" /></p> 
 <p>Zip Code: <input type="text" name="zipCode" id="city" size="5" /></p>


If it feels like a fairly common piece of code, that's right. That's exactly what it is! When you enter a new value in the City or State field,callServer()The method is triggered, so Ajax starts to run. I know what's going on, right? Okay, that's it!


Now you may have prepared to write the first Ajax application. At least I want to read the articles in the references carefully? However, you can start with the basic concept of how these applications work.XMLHttpRequestThe object has a basic understanding. In the next article, you will learn how to handle JavaScript and server communication, how to use HTML forms, and how to obtain Dom handles.

Now let's take a moment to consider how powerful Ajax applications are. Imagine what the web form will immediately respond to when you click a button, enter a field, select an option from the combo box, or drag the mouse over the screen. Think about itAsynchronousWhat exactly does it mean? Think about how JavaScript code runs andDon't waitThe server responds to its requests. What problems do you encounter? What kind of fields will it enter? Considering this new method, how should we change the form design during programming?

If you spend a little time on these issues, you will get more benefits than simply cutting/pasting some code into an application that you don't even understand. In the next article, we will put these concepts into practice and detail the Code required to make the application work in this way. Therefore, let's take a look at the possibilities of Ajax.

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: 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.