Dynamic Web pages and Ajax technology

Source: Internet
Author: User
Traditional web pages are HTML files, and their content will not change without refreshing the entire page. Some readers may ask if the web page can be as desktop Program What about rich and timely human-computer interaction functions? If you have used Google Map, Google suggest, or Gmail, you may realize that we are not far from this age. The concept of Web 2.0, which is so popular today, is actually to put it bluntly that desktop applications are networked. These applications can be said to be the pioneers of Web 2.0. They look and use similar to desktop programs, and their implementations do not rely on any plug-ins. What is this technology? So that Google can develop such a cool system-this is the Ajax technology introduced in this article.


Ajax Introduction

Ajax is short for Asynchronous JavaScript and XML. Ajax is not a new technology, but a combination of the three important features existing in Web browsers:

1. the browser can communicate with the Web server through JavaScript.
2. javascript can dynamically change the page value without refreshing a new page.
3. the browser can parse XML files.

As part of Ajax, these three features have existed for a long time until Google launched Google Map, Gmail and Google suggest, and Ajax became popular, so many people mistakenly believe that AJAX is a new technology invented by Google.

The traditional web page workflow is to send a request to the Web server by a browser. After receiving the data, refresh the entire page to display new data, as shown in:

What the user can do when performing operations on the server is to wait, so that the user's online operation experience is not as consistent as using the client program.

Using ajax, You can trigger JavaScript through events while performing operations, connect to the server in the background to obtain data, and dynamically change the page value without refreshing the entire page, the process is shown in:

The user performs operations on the user page, such as inputting in the input basket and clicking the button ...... All of these will generate events and trigger JavaScript. When Javascript is executed, you can use XMLHttpRequest to send an HTTP request to the server and obtain the HTTP response from the server. The content of the page is dynamically changed without refreshing the HTTP Response content. XMLHttpRequest is a defined object in the browser. It is the core component of Ajax technology. Javascript uses it to communicate with the server and parse the XML file passed back from the server. XMLHttpRequest was first implemented by Microsoft as an ActiveX object, and other popular browsers subsequently implemented XMLHttpRequest. When defining the XMLHTTPRequest object, ie is slightly different from other browsers, which will be described in the following example.

Learn how to use Ajax

This document uses an example to describe Ajax. In this example, a servlet on the server generates a 0 ~ An integer of 100. Users on the user end are required to enter 0 ~ in the input basket ~ 100. If the number is the same as the number automatically generated by the server, "Congratulations, you guessed it!" will appear on the page !" . At the same time as the user inputs, a prompt is displayed on the right side of the input basket to tell the user whether the input quantity is large or small. These prompts are dynamically completed without refreshing a new page. As shown in:

Next, we will compile the program and learn Ajax.

Preparation 1: Create a server Servlet

In this example, the servlet is called "validateguess" and Its URL pattern is/validateguess. this servlet can do the following:

1. randomly generate a 0 ~ An integer between 100.
2. when receiving an HTTP request, get the incoming number from the HTTP request, compare it with the integer generated in the previous step, and return the comparison result through HTTP response, the result is in the form of XML text, such:
......
<Message>
Toosmall
</Message>
......

Preparation 2: create user page Ajax. jsp

The page is very simple ,:

Note the following two points:

1. the input basket is defined as <input type = "text" id = "Guess" name = "ID" onkeyup = "Validate ()">, and onkeyup defines validate () the function is the listener of the keyup event. When you input the parameter in the input basket, The Validate () function is called. The program of the validate () function is as follows:
Function validate (){
VaR anumber = Document. getelementbyid ("Guess ");
VaR url = "http: /localhost: 8080/ajax/validateguess? Guess = "+ escape (anumber. value );
Initrequest ();
Sendrequest (URL );
}

The initrequest () and sendrequest () functions will be further explained in the following section.

2. there is a <Div id = "messagetext"> <div> on the right of the input basket, which is invisible at the beginning of JSP, its content dynamically appears and changes as user input.

Now that the preparation is complete, we can add JavaScript to Ajax. jsp to implement Ajax.

Step 1: Create an XMLHTTPRequest object

As mentioned above, XMLHttpRequest is an object defined in the browser. It is first implemented by Microsoft in ie5, and then supported by other mainstream browsers, therefore, when defining this object, ie is slightly different from other browsers, as shown in the following Program (only major program fragments are included in this article ):
......
VaR req;
Function initrequest (){
If (window. XMLHttpRequest) {// a browser other than IE
Req = new XMLHttpRequest ();
} Else if (window. activexobject) {// Internet Explorer 5.0 and up
Req = new activexobject ("Microsoft. XMLHTTP ");
}
}
......
Now, an XMLHTTPRequest object is obtained in Javascript. The following program can operate on the XMLHTTPRequest object named "req.

Step 2: Use XMLHttpRequest to send a request to the server

Function sendrequest (URL ){
Req. Open ("get", URL, true );
Req. onreadystatechange = handleresponse;
Req. Send (null );
}

In this step, several important XMLHttpRequest functions and parameters are called:

    • Open ("method", "url" [, asyncflag [, username [, password])

Open is a function of XMLHttpRequest. This function has five parameters, and the last three are optional parameters.

Method -- http request method, which supports "Post" and "get ".
URL: the URL of the server program.
Asyncflag -- determines whether the request is concurrent. If asyncflag = true, the send () function returns the request immediately after sending the request. If asyncflag = false, the send () function must return the request only after receiving the receipt. The default value is true.
Username -- User Name. Some URLs require a request with a user name, which is generally not used.
Password -- password; generally not used.

    • Readystate

Readystate is a parameter of the XMLHTTPRequest object, used to indicate the state of this object. There are five possible states:


0 uninitialized -- indicates that the open () function has not been called.
1 loading -- indicates that the send () function has not been called.
2 loaded -- indicates that the send () function has been called.
3 interactive -- indicates the status when the send () function is called but the requirement is not met.
4 completed -- the requirement is met.

After an XMLHTTPRequest object is created, its state is converted between these five values. Each state change triggers a readystatechange event. You can define a listener to process the event.

    • Onreadystatechange = handleresponse

Onreadystatechange is a parameter of the XMLHTTPRequest object. It defines the listenser when the state change event of this object occurs. Its value corresponds to a JavaScript function. In this example, our listenser is called "handleresponse ". Note that handleresponse is a function defined by you, but ensure that the onreadysatechange value is consistent with the function name defined by you.

XMLHttpRequest also has other parameters and functions, and readers who want to learn more can find detailed text and information about XMLHttpRequest in http://www.xulplanet.com/references/objref/xmlhttprequest.html.

Step 3: process the readystatechange event

As mentioned above, the onreadystatechange parameter of XMLHttpRequest is set to handleresponse. This function is called whenever the status of XMLHttpRequest changes, but we are only interested in readystate = 4 (completed. The handleresponse program is as follows:

Function handleresponse (){
If (req. readystate = 4 ){
If (req. Status = 200 ){
Processmessage ();
}
}
}

    • Status

Status indicates the XMLHttpRequest parameter, indicating the HTTP Request status. For example, 404 indicates that the server is not found, 500 indicates that the server program fails, and 200 indicates that everything is OK. When the readystate of XMLHttpRequest is 4 and the HTTP Request status is 200, you can call the processmessage () function to process the results returned by the server. The processmessage () program is as follows:

Function processmessage (){
VaR messageelement = Req. responsexml. getelementsbytagname ("message") [0];
VaR message = messageelement. childnodes [0]. nodevalue;
VaR mdiv = Document. getelementbyid ("messagetext ");
If (Message = "toobig "){
Mdiv. innerhtml = "<Div style =" color: Red "> too large </div> ";
} Else if (Message = "toosmall "){
Mdiv. innerhtml = "<Div style =" color: Red "> too small </div> ";
} Else if (Message = "invalid "){
Mdiv. innerhtml = "<Div style =" color: Red "> not a number </div> ";
} Else if (Message = "outofrange "){
Mdiv. innerhtml = "<Div style =" color: Red "> out of range </div> ";
} Else {
Mdiv. innerhtml = "<Div style =" color: Green "> congratulations, you guessed it! </Div> ";
}
}

The processmessage function does two things:

1. resolved the server return value

XMLHttpRequest automatically converts the XML from the HTTP response returned by the server into a tree-like Dom document structure and exists in the responsexml parameter. It can be used to parse the returned XML file and finally obtain the returned value. You can go to http: // www.xulplanet.com/references/objref/document.htmlto find the detailed text about Dom document.

2. dynamically update the page

As mentioned above, there is a <Div id = "messagetext"> on the right side of the input basket on the page. processmessage () dynamically changes its content through mdiv. innerhtml.

 

So far, a complete Ajax program has been developed. You only need to compile the complete source program and deploy it on the server to run it. AJAX can develop perfect applications like Google map, but its basic principle is actually very simple. Readers familiar with JavaScript only need to learn how to use XMLHttpRequest on the basis of the original. However, it takes a lot of effort to make full use of Ajax's potential and develop applications that are as skilled as Google map.

Ajax considerations

As a new generation of network page development architecture, Ajax makes it possible for us to develop pages with rich human-computer interaction functions. However, Ajax also has its shortcomings. Before you decide to use Ajax, make sure that the following Ajax deficiencies do not affect your application development:

1. Ajax is only supported by newer web browsers. If your applications need to support older Web browsers or mobile browsers, Ajax is not a good choice. The following is a browser that supports Ajax:

    • Microsoft IE 5.0 or above
    • Apple Safari 1.2 or above
    • Firefox 1.0 or above
    • Netscape 7.1 or above
    • Opera 7.6 or above

2. because Ajax is implemented without refreshing a new page, the address bar in the browser will no longer reflect the status of the current page. Therefore, the bookmarks function cannot guarantee that the user can access the page during the next visit, the same content can be obtained, and Ajax also breaks the "back" key in the browser.

3. If Ajax is improperly used, it will increase network data traffic without any need, thus reducing the performance of the entire system.

4. Javascript in Ajax is executed on the client and on the serverCodeDifferent, the Ajax code will be downloaded to the client. Be careful not to include sensitive information in the Ajax code to avoid leaks.

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.