Java programmers from stupid birds to cainiao ()

Source: Internet
Author: User


Ajax (Asynchronous JavaScript and XML), Asynchronous JavaScript and XML.The so-called synchronization,Before performing an operation, you must wait until the previous operation returns the operation result.AsynchronousThis means that an operation is not affected by the previous operation. The previous operation can be performed if any operation is returned. Each operation can be performed at the same time. For users, you don't have to wait. You don't have to wait for the previous operation to execute the new operation. Enhance the user experience. Asynchronous transmission is character-oriented transmission. Its unit is character, while synchronous transmission is bit-oriented transmission. Its unit is bytes, it requires that the receiver and the sender's clock be consistent during transmission. In fact, Ajax is not a new technology, but the assembly of some technologies. Ajax brings great benefits to our network. If we simply submit a form, we do not need to refresh the entire page, but only need to submit partial forms, refresh the local disk, which greatly reduces network traffic. It also has its disadvantages. The disadvantage is that the backward and forward buttons on the browser become invalid. If we have three asynchronous Ajax operations on the page, the browser does not treat it as three request operations, nor does it return three times back to the original page


The working principle of AJAX is equivalent to adding an intermediate layer between the user and the server, so that user operations and server responses are asynchronous. Not all user requests are submitted to the server, for example, some data verification and data processing are handed over to the Ajax engine, the Ajax engine submits requests to the server only when it is determined that new data needs to be read from the server.


The most important object in Ajax is XMLHttpRequest. This object was first provided by Microsoft in the form of plug-ins in IE, but Microsoft simply proposed such an object, it is not really practical. Later, other browsers also gave this object, but they all provide built-in objects instead of Simple plug-ins. Therefore, when obtaining this object, you cannot avoid using if .. Else determines whether an object exists in IE browser. This object is unique to IE and is the object of the Active Control. Through window. activexobject: Write this statement in the IF statement. In JavaScript, if it is not undefined or false, it is true. Therefore, if the active space exists, the IF condition is true. That is, IE browser. The XMLHTTPRequest object obtained by IE is a fixed form: XMLHttpRequest = new activexobject ("Microsoft. XMLHTTP "); this is a unique method for IE to obtain the XMLHTTPRequest object. If you want to obtain the XMLHTTPRequest object, you can use new directly, that is, XMLHttpRequest = new XMLHttpRequest (); although IE and other browsers obtain XMLHttpRequest objects in different ways, XMLHttpRequest is used in the same way.


Now, after judging the browser, we are ready to send a request to the server. To send a request, we use XMLHttpRequest. open ("Post", "ajaxservlet", true); the three parameters here are necessary. The first parameter indicates the form in which the request is sent, the second parameter is the request address. Here, Our address is a servlet. The third parameter specifies whether the request is sent asynchronously. Generally, we set this parameter to true.


After sending the message, we need to make it accurate. Ajax receives data in the form of a callback function. That is to say, after registering this callback function, when a certain requirement is met, it will automatically call this callback function and then execute the callback function content to register the callback function: XMLHttpRequest. onreadystatechange = ajaxcallback; note that this callback function does not contain parentheses. We can literally see that this callback function is called when the status is changed.


After everything is ready, we need to make a real send request. The Send request is the send method of the XMLHTTPRequest object called. In this method, when the request is sent in the form of post, the parameters of the method here are, it is the parameter of the requested address. The parameter of this address is passed as a key-value pair. If the request is in the form of get, we can set the parameter of the send method to null ., For example, if we send code in the form of a GET request: XMLHttpRequest. Send (null);, let's talk about the request in the form of a POST request. XMLHttpRequest. Send (null), null can be passed to the parameter (that is, send ("V1 =" + V1); and must be set before (XMLHttpRequest. Send (null)


XMLHttpRequest. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"); pay attention to this 1.1.


OK. After the request is sent, let's take a look at how we can accept the data returned by the request. According to the HTTP protocol, we should know that a request is divided into four steps, that is, a request has four states, and its state is the readstate attribute of the XMLHTTPRequest object. Let's take a look at the specific content of these five states:

From the above, we can see that the callback function we registered above will be executed four times, but we can only execute the content of our callback function when the request is complete, so we can make a judgment in the callback function.


If (XMLHttpRequest. readystate = 4) {// request completed }.

Although we have determined whether the request is complete, we do not know whether the request is successful. In our HTTP protocol, the request success status code is 200, so we can judge whether the status code is 200 as follows.

If (XMLHttpRequest. Status = 200 ){}

Okay. We have explained the Ajax execution process. Before looking at the specific code, let's take a look at the attributes of the XMLHTTPRequest object:

Next we will look at the example code of Ajax's entire execution process: We will use a calculator example to implement it:

First, let's take a look at the form code:

<input type="button" value="add"onclick=ajaxSubmit();;><br><input type="text" name="value1" id="value1ID"><br><input type="text" name="value2" id="value2ID"><br><div id="div1"></div>

Then let's take a look at the JavaScript code executed by Ajax:

<SCRIPT type = "text/JavaScript"> var XMLHttpRequest = NULL; // declare an empty object to receive the XMLHTTPRequest object function ajaxsubmit () {If (window. activexobject) // IE browser {XMLHttpRequest = new activexobject ("Microsoft. XMLHTTP ");} else if (window. XMLHttpRequest) // implement {XMLHttpRequest = new XMLHttpRequest ();} If (null! = XMLHttpRequest) {var V1 = document. getelementbyid ("value1id "). value; var v2 = document. getelementbyid ("value2id "). value; // when the get method is used to access the server with parameters, the parameter is directly added after "ajaxservlet". The following send method can be set to null, the post method must add the parameter to the send parameter, as shown in XMLHttpRequest. open ("Post", "ajaxservlet", true); // associate the Ajax callback function XMLHttpRequest. onreadystatechange = ajaxcallback; // actually sends data to the server. // If the POST method is used for submission, you must add the following line. You do not need to add this XMLHttpRequest to the get method. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded"); XMLHttpRequest. send ("V1 =" + V1 + "& v2 =" + V2) ;}} function ajaxcallback () {// the status of each Ajax request changes four times, therefore, if (XMLHttpRequest. readystate = 4) {// If (XMLHttpRequest. status = 200) {var responsetext = XMLHttpRequest. responsetext; document. getelementbyid ("div1 "). innerhtml = responsetext ;}}</SCRIPT>

Finally, let's take a look at the server execution:

In the dopost Method

String v1 = req.getParameter("v1");String v2 = req.getParameter("v2");System.out.println("v1=" + v1 + ", v2=" + v2);String v3 = String.valueOf(Integer.valueOf(v1) + Integer.valueOf(v2));PrintWriter out = resp.getWriter();resp.setHeader("pragma", "no-cache");resp.setHeader("cache-control", "no-cache");out.println(v3);out.flush();

Below we will summarize the advantages of Ajax:

1. reduce the burden on the server. Because the fundamental idea of AJAX is to "retrieve data on demand", it is possible to minimize the burden on servers caused by redundant requests and sound shadows;

2. The page is refreshed to reduce the user's actual and psychological waiting time;

3. Some previous server workload can also be transferred to the client, which facilitates the idle processing capability of the client, reduces the server and bandwidth burden, and saves space and bandwidth rental costs;

4. Ajax separates the web interface from the application (or data and presentation separation );

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.