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 article 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 is not just a fashion, it is a powerful way to build websites, and it is not as difficult as learning a brand new language.
But before discussing in detail what Ajax is, let's take a few minutes to understand what Ajax is doing. 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 Amazon.com 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.
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 use Div, span, and 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.
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 explanation, it is not an acronym.
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 is, XMLHttpRequest. 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 ();
</SCRIPT>
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 reading more, stop and think about it: javascript technology is used to talk to the server through the XMLHTTPRequest object. This is not a general application stream, but a source of powerful Ajax functions.
In a common web application, enter the form field and click the submit button. 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.
Ajax basically stores JavaScript and XMLHttpRequest objects between web forms and servers. When a user fills out a form, the data is sent to some JavaScript code instead of directly 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 is the power of XMLHttpRequest. 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
After obtaining the XMLHttpRequest handle, other 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.
You must be familiar with the getelementbyid () method for the first two points, 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 mastered XMLHttpRequest, the rest 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. Dom is widely used in complex 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. XMLHttpRequest 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 it is strange that XMLHttpRequest has become one of the victims of the war. Therefore, you may need to use different methods to obtain the XMLHTTPRequest object. 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 creates an XMLHttpRequest on the Microsoft browser.
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 ");
And
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 successful, set the XMLHTTP variable to false to tell you that the Code has a problem. 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 creates XMLHttpRequest objects in Mozilla, Firefox, Safari, opera, and basically all non-Microsoft browsers that support Ajax in any form or method.
Combined
The key is to support all browsers. 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, regardless of the strange symbols commented out, such as @ cc_on, this is a special JavaScript compiler command and will be discussed in detail in the next article on XMLHttpRequest. The core of this Code is divided into three steps:
1. Create a variable XMLHTTP to reference the XMLHTTPRequest object to be created.
2. Try to create this object in Microsoft browser:
1) try to create it using the msxml2.xmlhttp object.
2) if it fails, try the Microsoft. XMLHTTP object again.
2. If XMLHTTP is still not created, this object is created in non-Microsoft mode.
Finally, XMLHTTP should reference a valid XMLHTTPRequest object, regardless of the browser that runs.
Security
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.
AjaxRequests/responses in the world
Now we have introduced Ajax and a basic understanding of the XMLHTTPRequest object 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 Use XMLHttpRequest. Because this code is very important, every Ajax application you write must use it in some form. Let's take a look at what the basic Ajax request/response model is like.
Send request
You already have a brand new XMLHTTPRequest object. 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 completes.
5. Send a request.
Listing 5The example Ajax method in 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
VaR url = "/scripts/getzipcode. php? City = "+ escape (city) +" & State = "+ escape (State );
// Open a connection to the server
XMLHTTP. Open ("get", URL, true );
// Setup a function for the server to run when it's done
XMLHTTP. onreadystatechange = updatepage;
// Send the request
XMLHTTP. Send (null );
}
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 see that XMLHttpRequest is used. The connection method (get) and the URL to be connected are specified. If the last parameter is set to true, an asynchronous connection is requested (this is the origin of Ajax ). If false is used, the code sends a request and waits for the response from the server. If this parameter is set to true, you can still use forms (or even call other Javascript methods) when the server processes requests in the background ).
The onreadystatechange attribute of XMLHTTP (Remember, this is an XMLHTTPRequest object instance) can tell the server what to do after it is completed (it 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 finishes processing the request, a special method named updatepage () will be triggered.
Finally, use null to call send (). 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 not do anything until the value of the XMLHTTP. readystate attribute is 4.
·The server fills in the response to the XMLHTTP. responsetext attribute.
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, use the XMLHTTP. responsetext attribute 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. The zipcode field containing the zip code suddenly appeared, and the user did not press any button! 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 notice that zipcode is a common text field. Once the server returns the zip code, the updatepage () 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 so: Keep the example simple, indicating that users may want to modify the data returned by the server. Remember these two points. They are important for good user interface design.
ConnectionWebForm
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 on calling the first JavaScript method, which 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
<Form>
<P> City: <input type = "text" name = "city" id = "city" size = "25"
/> </P>
<P> state: <input type = "text" name = "state" id = "state" size = "25"
/> </P>
<P> zip code: <input type = "text" name = "zipcode" id = "city" size = "5"/> </P>
</Form>
If it feels like a fairly common piece of code, that's right. That's exactly what it is! When a user enters a new value in the City or State field, the callserver () method is triggered and Ajax starts to run. I know what's going on, right? Okay, that's it!
Conclusion
Now you may have prepared to write the first Ajax application. At least read it carefully.ReferencesWhich of the following articles? However, you can first have a basic understanding of the XMLHTTPRequest object from the basic concepts of how these applications work. 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 what asynchronous means, think about JavaScript code running, and don't wait for the server to respond 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.