How does Ajax come into being? How has Ajax been developed? (concluding article)

Source: Internet
Author: User
Tags function prototype

This article mainly introduces the background definition of Ajax and the summary of personal use of Ajax, so let's take a look at this article.

This article has the following content:

    • What is Ajax

    • Background of the advent of Ajax

    • The principle of Ajax

    • Definition of Ajax

    • The development steps of Ajax

    • A simple Demo

    • The pros and cons of Ajax technology

  What is Ajax?

By looking at Wikipedia we can see something like this:
Ajax, "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML technology), refers to a set of browser-side web development techniques that combine a number of technologies.

Well, now we have a general impression, Ajax=javascript+xml. and JS and XML should not be unfamiliar to us.
   background of the advent of Ajax
Looking back on our development journey, our web App allows users to fill out and submit forms (form) on the Web page to send requests (request) to the Web server during the original development process using Servlet+jsp+javabean. The server receives the request and processes the incoming form, returns the response (Response), and after the browser responds, the page is displayed on the browser by parsing, thus completing a user interaction with the server.
However, there are some problems with this model. Now look at an example: The browser side shows the user login interface, when the user entered the user name, password and verification code, the data was sent to the server, assuming we processing the request in the servlet found that the user name and password does not match, what will we do next?
We re-return the page with the response to the error message to the browser, and the browser presents the information after parsing the response, using a development process that has some inherent problems, no matter how perfect the business implementation may be:
First of allwasting bandwidth. The other elements are all the same in the front and back two pages except for the part where the error message is displayed.
SecondlyThe user experience is poor. Suppose that the user accidentally entered the wrong user name in the form, after the submission of the form will appear after waiting for a period of time after the page was refreshed, and prompted the user name error, so that users have to re-enter the user name and password, the experience is very unfriendly. The user experience is even worse when the user's network speed is slow.
So is there any way to solve this problem? That is, can the user just enter the user name to get feedback?
   The general idea of Ajax
JS XMLHttpRequest object Before there is no way, but after it appeared, the predecessors thought of a better solution, that is: using the XMLHttpRequest object as an agent to send the request to the server, and use it to receive the data returned by the server, This will not jump to the page to complete the interaction of data, and only need to transfer a small amount of necessary data, so the requirements of the speed is also lower.
However, there are two issues that are not resolved:
1. How do I dynamically change the page based on the data returned from the server to achieve interaction with the user?
2. How to specify the data format that the server sends back, make it more generic, and transmit as little as possible?
For 1: Seniors have chosen to use JavaScript, and there are two reasons why they do this, first, JavaScript is popular enough, and almost all mainstream browsers support JavaScript; JavaScript can dynamically change the contents of a Web page by using the DOM programming method.
For 2: Seniors chose XML, and I think it might be because it's grammatically rigorous, semantically explicit, and more generic. But I think the transmitted data format has no effect on using AJAX. For example, we can choose to transfer the JSON to make the transmitted data less, and even choose to transfer a meaningful string, as long as the server-side and browser-side developers to the format of the contract.
   Ajax Definitions
Now, we can define Ajax:AJAX is a technique for creating fast, Dynamic Web pages. AJAX enables Web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means that you can update a part of a webpage without reloading the entire page.
   the development steps of Ajax technology
Through the above introduction, we know the solution to the traditional problem of resource waste, now look at how to achieve it!
About AJAX implementation, you can go to see W3school about AJAX Introduction
Here is a brief summary of the AJAX implementation steps:
1. We need a XMLHttpRequest object. (We all know that the standard of IE's low-version browsers is not compatible with mainstream standards.) Unfortunately, the same is true for XMLHttpRequest objects ....)
Thus, the acquisition of a XMLHttpRequest object is this:

    var httpxml = null;    if (window. XMLHttpRequest) {        httpxml = new XMLHttpRequest ();  For modern browsers, IE7 and above version    }else if (window. ActiveXObject) {        httpxml = new ActiveXObject ("Microsoft.XMLHTTP");  For IE5,IE6 version    }

2. We need to register it for this XMLHttpRequest object (through callbacks) and view the status of the message based on the requested status and HTTP status code returned, and determine under what circumstances we are going to do it. (Want to see more on the Topic.alibabacloud.comAJAX Development Manual section of the study)

The process is like this:

    Register the onReadyStateChange property of the XMLHttpRequest object    httpxml.onreadystatechange=function () {        //  In the callback function, according to the request status and return HTTP status code to select the appropriate action processing data        if (httpxml.readystate==4&&httpxml.status==200) {            alert ( Httpxml.responsetext);        }    };

3. We need to make the parameter settings for the request send.
The process is like this:

    Function prototype: Open (Method,url,async,username,password)    //method            ---> Request method: Get,post or head    //url               --- > Requested address  get Submit method can be appended with the parameter    //async             ---> whether the request is executed asynchronously, true---asynchronous, false---synchronization   defaults to True    //username , Password---> Optional to provide certification for the authorization required for the URL. If not empty, the qualified    httpxml.open ("GET", "Http://localhost:8080/aaa/MyServlet", true) specified in the URL will be overwritten;

4. To really send a request!

      parameter is the request parameter, the post submission content format is---> "username=taffy&password=666", get is-----> empty    //  Note: If it is a POST request mode, You also need to set up an HTTP request header (which should be located after open, before send)    //i.e. setRequestHeader ("Content-type", "application/x-www-form-urlencoded");    The Enctype property of the Sign form form        httpxml.send (null);

In this way, a simple Ajax process is done.
Some little points of knowledge that are not covered:

    XMLHttpRequest Property    responsetext   Gets the returned text information    Responsexml    The method    of getting the returned XML information//xmlhttprequest getResponseHeader ()   Gets the specified header information    getallresponseheaders () a    control method that returns the HTTP response header as an unresolved string//xmlhttprequest    abort ()    cancels the current response, closes the connection, and readystate 0

Here is a simple demo of what I did:

Register.html
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

 
   Myservlet.java 
  

Import Java.io.ioexception;import Java.io.printwriter;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * servlet implementation Class Myservlet */@WebServlet ("/myservlet") public class Myservlet extends HttpServlet {private static final long seria    Lversionuid = 1L;    /** * @see httpservlet#httpservlet () */public Myservlet () {super (); } @override protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception,        IOException {PrintWriter out = Response.getwriter ();        String username = request.getparameter ("user"); if (Username!=null&&!username.equals (")") {if (Username.equals ("admin")) {Out.write ("t            Rue ");            }else {Out.write ("false"); }}else {out.Write ("false");    } out.close ();  } @override protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception,    IOException {doget (request, response); }}

* Below the pros and cons of Ajax to summarize: *
Advantages:
The ability to maintain data without updating the entire page. This allows the Web application to respond more quickly to user actions and avoids sending information that is not changed on the network.
Disadvantages:
1. It may corrupt the browser's fallback function. In the case of dynamically updating the page, the user cannot go back to the previous page state, because the browser can only write down the static pages in the history (modern browsers generally solve this problem);
2. Using dynamic page updates makes it difficult for users to save a specific state to the Favorites folder.

This is the end of this article (want to see more on the Topic.alibabacloud.comAJAX User manual section of the study), there are questions can be in the message below the question.

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.