Starting from scratch Ajax (iii) AJAX overview, get started quickly

Source: Internet
Author: User

Hello everyone, here is "learn the Web series from scratch" and synchronize updates at the following address ...

  • Github:
  • Public number: The top of the Web front
  • Blog Park:
  • csdn:

Here I will start with the Web front End 0 Foundation, step-up learning web-related knowledge points, during the period will also share some fun projects. Now let's go to the Web Front end learning Adventure tour!

I. Overview of AJAX

Ajax Full Name: Asynchronous JavaScript and XML (asynchronous JavaScript and XML). It is not a new programming language, but a technique for creating better, faster, and more interactive Web applications. It provides the ability to update parts of a Web page without reloading the entire page. Traditional Web pages (without AJAX) must reload the entire Web page if you need to update the content.

And why is it called async?

Because at the time of loading, the other parts of the page are still free to operate, and there is no card-dead state, so it is asynchronous.

There are many examples of applications that use AJAX: Sina Weibo, Google maps, happy net, and more.

Before that, there are several ways we can get the browser to make a request to the server and get the data from the server:

    • Address bar input address, enter, refresh
    • href or src attribute of a specific element
    • Form submission

These scenarios are either impossible or difficult to program in code (a response to a server that makes a request and accepts a return from the server).

If you look closely at the submission of a form, you will find that once the user clicks the "Submit" button and the form is submitted, the browser refreshes the page and tells you whether the operation succeeded or failed in the new page. If unfortunately because the network is too slow or other reasons, you will get a 404 page.

This is how the Web works: one HTTP request corresponds to a page.

If you want to leave the user on the current page and make a new HTTP request, you must send the new request with JavaScript, receive the data, and then update the page with JavaScript, so that the user feels that he is still on the current page, but the data can be constantly updated.

The first large-scale use of Ajax is the Gmail,gmail page after the first load, all the rest of the data is dependent on Ajax to update.

Writing a complete Ajax code with JavaScript is not complicated, but it is important to note that the AJAX request is executed asynchronously, that is, to get a response from the callback function.

Second, Ajax quick to get started

The process of using Ajax can be analogous to the usual way we visit Web pages:

// 1. 创建一个 XMLHttpRequest 类型的对象 —— 相当于打开了一个浏览器            var xhr = null;            if (window.XMLHttpRequest) {                xhr = new XMLHttpRequest();            } else {                xhr = new ActiveXObject("Microsoft.XMLHTTP");            }// 2. 打开与一个网址之间的连接 —— 相当于在地址栏输入访问地址  "get", "checkusername.php?username=" + uname, true);// 3. 通过连接发送一次请求 —— 相当于回车或者点击访问发送请求            xhr.send(null);            // 仅仅针对 post 请求            //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');// 4. 指定 xhr 状态变化事件处理函数 —— 相当于处理网页呈现后的操作            xhr.onreadystatechange = function () {                if (this.readyState == 4) {                    if (this.status == 200) {                         console.log(this.responseText);                    }                }            };
1. Create objects

In the IE6 and below, is not support XMLHttpRequest object, then the corresponding wording is:

var xhr = new ActiveXObject("Microsoft.XMLHTTP");

So for compatibility, the above-created object is changed to:

var xhr = null;if(window.XMLHttpRequest) {    xhr = new XMLHttpRequest();} else {    xhr = new ActiveXObject("Microsoft.XMLHTTP");}
2. Open method

The first parameter is the way it is requested, whether it is a GET request or a POST request. It is generally the case that the backend developer's PHP file is either get or post.

The second parameter is the address that needs to be requested. If it is a GET request, you need to add it after the address. To connect, connect to your content that needs to be requested. (Refer to the example below to verify the username), if it is a POST request, just write the requested address, and its request content is written in send.

The third parameter is synchronous or asynchronous, which can generally not be written, not write default async, false: Synchronous, true: asynchronous.

3. Send method

For Get mode, the parameter is null;

For post mode, the parameter is the requested data.

var param = "username=" + uname; // 和 get 地址后面 ? 链接请求内容一致shr.send(param);

For post requests, you also need to set the next request header (only for post requests)

// 仅仅针对 post 请求才有xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
4. onreadystatechange callback function

It is a callback function that does not block the current operation, when the server returns data, and when it is used. This is asynchronous.

Status: State code returned by the server

This.status = = 200: Indicates a successful response, 404 indicates that the requested resource was not found, and 500 indicates a server-side error.


When the state of the XHR object changes, the value of the readystate changes accordingly. The meanings of the specific values are shown in the following table:

readyState XHR Status Description
0 Unsent Agent (XHR) was created, but the open method has not been called
1 Opened The open method has been called to establish a connection
2 Headers_received The Send method has already been called to get the status line and the response header
3 LOADING In the response body download, the ResponseText property may already contain some data
4 Done The response body download completes, can call ResponseText to obtain the data directly

Detailed parsing code:

  var xhr = new XMLHttpRequest (); Console.log (xhr.readystate);/= 0//Initialize Request proxy object (' GET ' , ' time.php '); Console.log (xhr.readystate);//= 1//The Open method has been called to establish a connection to a specific port on the server Xhr.send (); Xhr.addeventlistener ('        ReadyStateChange ', function () {switch (this.readystate) {Case 2://= + 2//response header has been received for the response message        Can get head//Console.log (This.getallresponseheaders ()) Console.log (This.getresponseheader (' server '));        But has not yet got body console.log (this.responsetext);                Break Case 3://= 3//is downloading the response body of the response message, it is possible that the response body is empty, or it may be incomplete//where the response body is not insured (unreliable) Console.log (this.respo        Nsetext);                Break        Case 4://= 4//All OK (the entire response message has been completely downloaded)//Here The response body Console.log (this.responsetext) is processed;    Break }});

When readyState = = 2 o'clock, only gets the data header, this time cannot use the responsetext obtains, but uses the getResponseHeader to obtain the data header information.

When readyState = = 3 o'clock, may have obtained some data body, but processing data is unreliable, so generally we are in the readyState value of 4 o'clock, the execution of the subsequent logic of the response.

In fact, when onreadystatechange execution and readyState = = 4, there is a more convenient wording in HTML5:

xhr.onload = function () {    console.log(this.readyState); // 4    console.log(this.readyState);}
Third, Case: Click the button to verify the existence of the user name
<! DOCTYPE html>

Background PHP Code:

<?php $user = $_GET["username"]; if($user == "lvonve") { // 这里仅仅只判断一个用户名,实际上是由数据库提供 echo "用户名已存在!"; } else { echo "用户名可以使用!"; }?>

Starting from scratch Ajax (iii) AJAX overview, get started quickly

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: 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.