A simple example teaches you to uncover the Ajax veil

Source: Internet
Author: User
Tags define object connect return string window client
Ajax


This article uses a simple example to illustrate how to use AJAX techniques in IE6. In this example, the client retrieves a random string from the server for every 10 seconds and automatically updates part of the page content without refreshing the page. The example uses only two JSP files, client.jsp and server.jsp.

AJAX, the abbreviation for "Asynchronous JavaScript and XML", can be translated into asynchronous JavaScript and XML technology. Its core is a class hosted in the browser named XMLHttpRequest. This allows you to connect to the server without submitting the form, and you can dynamically update portions of the page without refreshing the entire page. XMLHttpRequest usually use XML as a carrier of data interchange, but other vectors, such as plain text, can also be used. In short, it is through the XMLHttpRequest to send information to the server, the asynchronous receiving server processing and return information, and then dynamically update the page through JavaScript part of the content.

Although Ajax has been hot lately, Ajax is not a new technology, as its name shows, it's just JavaScript plus XML technology. And it's very simple to use.

The process of applying Ajax:
1. Define an event handler
2, get XMLHttpRequest, and register the event handler to it
3, connect with the server
4, send the information
5, the server returned processing information
6, whenever the state of XMLHttpRequest change, automatically trigger event handlers
7. Event Processor Dynamic Update page

This article uses a simple example to illustrate how to use AJAX techniques in IE6. In this example, the client retrieves a random string from the server for every 10 seconds and automatically updates part of the page content without refreshing the page. The example uses only two JSP files, client.jsp and server.jsp. For the convenience of illustration, I use server.jsp to replace the Server.java that should be used as a servlet.

First look at the client.jsp content:

<% @ page contentType = "text / html"%>
<% @ page pageEncoding = "gb2312"%>

   "http://www.w3.org/TR/html4/loose.dtd">


    
        <meta http-equiv = "Content-Type" content = "text / html; charset = gb2312">
        
        <script language = "JavaScript">
            var xmlHttp;
            
            function getGiftFromServer () {
                var url = "http: // localhost: 8084 / ajax / server.jsp";
                if (window.ActiveXObject) {
                    xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
                }

                xmlHttp.onreadystatechange = showGift;

                xmlHttp.open ("GET", url, true);
                xmlHttp.send (null);
                
                setTimeout ("getGiftFromServer ()", 10000);
            }

            function showGift () {
                if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
                    document.getElementById ("output"). innerHTML = "Time is for" + xmlHttp.responseText + ".";
                }
            }
        </ script>
    
    

        
AJAX example




When the page is loaded, JavaScript's getGiftFromServer () function will be called. This function completes steps 1 to 4 in the process of applying AJAX mentioned above, and sets a timer that automatically calls this function every ten seconds. The showGift () function completes steps 5 to 7 of the proposed process. Each step is explained in detail below.

1. Define an event handler. This handler will be automatically triggered when the server returns data.
    function showGift () {
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
            document.getElementById ("output"). innerHTML = "Time is for" + xmlHttp.responseText + ".";
        }
    }

Because we use asynchronous here, the readyState property is used to determine the state of the information returned by the server. Its value is an integer from 0 to 4, corresponding to:

    0: The object was created but not initialized (the open () method was not called)
    1: The object was created, but the send () method was not called
    2: The send () method has been called, but status and headers are not yet available
    3: Some data has been returned, but status and headers are not yet fully available
    4: All data has been received, all data can be used


2. Get XMLHTTPRequest and register event handler with it

Note: To use XMLHTTPRequest, you need IE5.0 or later.

2.1 Get XMLHTTPRequest

To get XMLHTTPRequest before IE7.0, use the following code:
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
    }

And in IE7.0:
    if (window.XMLHttpRequest) {
       xmlHttp = new XMLHttpRequest
    }

2.2 Registering an event handler
xmlHttp.onreadystatechange = showGift;

showGift is the method name passed in. This method will be executed whenever the state of XMLHTTPRequest changes

3. Connect with server and send

xmlHttp.open ("GET", url, true)

Its method signature is as follows:

xmlHttp.open (bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword)

among them:
    bstrMethod: connection method, available are GET, POST, PUT, or PROPFIND
      bstrUrl: URL of the server
      varAsync (optional): whether the call is asynchronous, the default is true (the call returns immediately)
    bstrUser (optional): user name, if the URL needs authentication
    bstrPassword (optional): password, if URL needs to be verified

The open () method can directly open an xml document and read the corresponding node through the responseXML of xmlHttp. The following example:
    xmlHttp.open ("GET", "http: //localhost/books.xml", false);
      xmlHttp.send ();
      var book = xmlhttp.responseXML.selectSingleNode ("// book [@ id = 'bk101']");

4.Send a message
xmlHttp.send (null)

Its method signature is as follows:
xmlHttp.send ([varBody])

    varBody (optional): can be data such as strings or xml, and can be null. No return value

This method returns immediately when open () is set to asynchronous; when open () is set to synchronous, it must wait until the response object returns from the server.

5. The server returns the processed information

At this point, it's server-side work. The code for server.jsp is as follows:

Pick a random one from the three strings, write it into the response, and return it to the client.

6. The client automatically detects that the state of the XMLHTTPRequest has changed, and automatically triggers the event handler.

Event handler dynamically updates the page

The processor reads the value of xmlHttp.responseText and updates it dynamically via JavaScript
Content.

document.getElementById ("output"). innerHTML = "Time is for" + xmlHttp.responseText + ".";
Conclusion:

As can be seen from the previous 7 steps, AJAX is not complicated, and it is much simpler than imagined. Keeping this in mind, "AJAX allows us to dynamically update part of the web page without refreshing the page", and then applied to various occasions where this performance is needed will make our web page more creative .

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.