AJAX introduction and getting started instances

Source: Internet
Author: User

For a newbie like me who is new to Web development and has little practical project experience, AJAX technology is complex and profound. After two days of baidu and google, I have a general understanding of the basic principles of AJAX.

1. What is AJAX?
AJAX stands for Asynchronous JavaScript and XML, and is short for Asynchronous JavaScript and XML. AJAX technology is used to create interactive web page applications for website development. As to what is asynchronous, I will explain it later.

1.1 desktop and Web applications
Before discussing AJAX technology in detail, we need to first know what AJAX technology is used. Currently, there are two basic types of applications:

Desktop Application)
Web Application)
Desktop applications can be obtained from the Internet or CD and need to run on desktop computers, such as some common PC software. Different from Web applications, Web application engineers run on a Web server somewhere, so they need to access such applications through a Web browser.

However, what is more important than where the code of these applications runs is how the applications run and how they interact with them. Desktop applications are generally fast and have beautiful user interfaces and extraordinary dynamics. You can click, select, open menus and sub-menus, and move around without waiting. On the other hand, web applications (such as Amazon.com and eBay) provide services that cannot be implemented by desktop applications. However, with the strength of the Web, wait for the server to respond, wait for the screen to refresh, wait for the request to return and generate a new interface.

The emergence of AJAX is to alleviate the problem of waiting for Web applications compared with desktop applications.

1.2 AJAX-old technology, new face
AJAX is not a new technology, but the integration of several other existing technologies.

AJAX applications use the following basic technologies:

Use HTML and CSS to create a Web form and display webpage information;
Use JavaScript to operate the DOM (Document Object Model) for Dynamic Display and interaction;
Use the XMLHttpRequest object for asynchronous data exchange with the Web server;
Use XML for data exchange and related operations;
Use JavaScript to bind everything together.
Let's further analyze the responsibilities of these technologies. Currently, 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
Copy codeThe Code is as follows:
<Script language = "javascript" type = "text/javascript">
<! --
Var xmlHttp = new XMLHttpRequest ();
// -->
</Script>

We will learn more about this object in the future. Now we need to know that this object is used to process communication between all servers. 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: it is also very easy to update the form, such as setting the field value or quickly replacing the image.
Parse HTML and XML: use JavaScript code to manipulate the DOM 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
Copy codeThe Code is as follows:
// 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.

2. What are the advantages and disadvantages of AJAX?
2.1 Advantages of AJAX
The biggest advantage of AJAX is that data can be maintained without updating the entire page. This allows Web applications to give feedback to user requests more quickly, improve user experience, and avoid sending unchanged information on the network.

Traditional Web applications allow users to enter forms. When a form is sent, a request is sent to the Web server. The server receives and processes the form and sends it back to a new web page. However, this method wastes a lot of bandwidth, because: after the two processes, the feedback page is summarized, most HTML code is usually the same. Because each application communication request needs to be sent to the server, the response time of the application depends on the response time of the server for a long time, which causes the user interface response to be much slower than that of the local application.

In contrast, an AJAX application can only send and retrieve necessary data to the server. It uses SOAP or some other XML-based page service interfaces (interfaces ), the client uses JavaScript to process responses from the server. Because a large amount of data is exchanged between the server and the browser (about 5% of the original data), we can see the response (Server Response) faster application (result ). At the same time, a lot of processing work can be done on the client machine that sends the request, so the processing time of the Web server is also reduced.

2.2 disadvantages of AJAX
The main criticism corresponding to AJAX is that it may damage the normal behavior of the browser's back button. When a page is dynamically updated, the user cannot return to the status of the previous page, because the browser can only write down the static page in the history. The difference between a fully read page and a dynamically modified page is very subtle: users usually want to click the back button to cancel their previous operation, however, you may not be able to do this on the AJAX page. However, developers have come up with various solutions to solve this problem. Most of them create or use a hidden IFRAME to reproduce the changes on the page when the user clicks the back button to access the history. (For example, when a user clicks back in Google Maps, it searches in a hidden IFRAME and then reflects the search result to the AJAX element, to restore the application status to the current state .)

Another related opinion is that using dynamic page updates makes it difficult for users to save a specific status to favorites. The solution to this problem has also appeared. Most of them use the URL snippet identifier (usually called the anchor, that is, the # part following the URL) to keep track, allows the user to return to the status of a specified application. (Many browsers allow JavaScript to dynamically update the anchor, which allows Ajax applications to update the anchor while updating the display content .) This solution also resolves a lot of arguments about not supporting the back button.

During AJAX development, network latency-that is, the interval between the user sends a request to the server for response-requires careful consideration. Users who do not give explicit responses, do not have proper pre-read data, or improperly process XMLHttpRequest may feel delayed. This is what users do not want to see and cannot understand. The common solution is to use a visual component to tell the user that the system is performing background operations and reading data and content.

3. General AJAX application process
3.1 create a 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. Unfortunately, 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 Internet Explorer uses the MSXML parser to process XML. 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
Copy codeThe Code is as follows:
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. 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 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.

Universal cross-browser Approach

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
Copy codeThe Code is as follows:
/* 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:

Create a variable xmlHttp to reference the XMLHttpRequest object to be created.
Try to create this object in Microsoft browser:
Try to create it using the Msxml2.XMLHTTP object.
If it fails, try the Microsoft. XMLHTTP object again.
If xmlHttp is still not created, this object is created in a non-Microsoft manner.
Finally, xmlHttp should reference a valid XMLHttpRequest object, regardless of the browser that runs.

3.2 client request/Server Response Mechanism of AJAX technology
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:

Obtain the required data from the Web form.
Create the URL to be connected.
Open the connection to the server.
Set the function to run after the server is complete.
Send a request.
The example Ajax method in listing 5 is organized in this order:

Listing 5. Sending Ajax requests
Copy codeThe Code is as follows:
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
Copy codeThe Code is as follows:
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.


3.3 [outside question] how to connect to a Web form
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
Copy codeThe Code is as follows:
<Form>
<P> City: <input type = "text" name = "city" id = "city" size = "25"
OnChange = "callServer ();"/>
<P> State: <input type = "text" name = "state" id = "state" size = "25"
OnChange = "callServer ();"/>
<P> Zip Code: <input type = "text" name = "zipCode" id = "city" size = "5"/>
</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!

4. What are the problems facing AJAX application development? How can this problem be solved?
For programmers, the biggest headache for developing Ajax applications is the following:

In essence, Ajax is a browser technology. The first unavoidable problem is browser compatibility. The support for JavaScript, DOM, and CSS in various browsers is always slightly different or has bugs. Even different versions of the same browser may have different support for JavaScript, DOM, and CSS. This leads programmers to spend most of their time writing Ajax applications in debugging browser compatibility rather than in the application itself.
The main purpose of Ajax technology is to locally exchange data between clients and servers. Like the traditional master-slave architecture, some business logic is inevitably implemented on the client, or some on the client on the server. Because the business logic may be dispersed on the client and server and implemented in different programming languages, Ajax applications are extremely difficult to maintain. Ajax applications often become a programmer's nightmare if user interfaces or business logic are more dynamic, coupled with the compatibility of JavaScript/DOM/CSS. To solve the problem of scattered business logic, Ajax development frameworks can be divided into two categories:
Put the business logic and presentation layer in the browser and the data layer on the server: because all programs are executed on the client using JavaScript, services are requested only when data is required, this method is also called the fat client architecture. In this architecture, servers are generally only used to provide and store data. The advantage of this method is that programmers can make full use of JavaScript with business logic to make special user interfaces to meet the requirements of end users. However, there are also many problems. The primary cause is that the JavaScript language itself may not be able to handle complex business logic. Second, the execution efficiency of JavaScript has always been poor. Third, JavaScript access to server data requires proper server-side programs. Fourth, the browser compatibility problem occurs again. Some Ajax development frameworks such as DWR attempt to automatically generate JavaScript to avoid compatibility issues, and open a channel so that JavaScript can directly call the Java program on the server side to simplify data access. However, the first and second problems still exist. programmers must make considerable effort to meet the specification requirements of the application, or may not be able to meet the requirements at all.
Put the presentation layer, business logic, and data layer on the server, and the browser only has the User Interface engine. This method is also called the thin client architecture, or the server-centric architecture. The browser's User Interface Engine is only used to reflect the server's performance Layer and convey user input back to the server's performance layer. Events triggered by the browser are also sent back to the server for processing. The presentation layer is updated based on the business logic and then reflected back to the browser. Because all applications are fully executed on the server, and data and performance layers can be directly accessed, programmers only need to use a relatively mature programming language (such as the Java language) on the server side, it is easier to develop applications without learning JavaScript, DOM, and CSS. The disadvantage is that the user interface engine and the presentation layer usually exist in the form of standard components. If special components (user interfaces) are required, they must be provided by the developers of the original framework. For example, the open-source Ajax development framework ZK currently supports XUL and XHTML components and does not yet support XAML.
Ajax submits requests to the server asynchronously. For the server, it is not different from the traditional form submission requirements, and because it is submitted in asynchronous mode, if there are multiple Ajax requirements and form submission requirements at the same time, it cannot be ensured that the server response is obtained first. This will cause a typical multi-process or multi-thread competition (racing) Problem in the application. Therefore, programmers must handle the problem themselves or use JavaScript to prevent such competition (for example, disable the button before Ajax requests are not responded ), this does not need to increase the burden on programmers. Currently, ZK is the only development framework that is known to automatically handle this problem.

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.