How Ajax works

Source: Internet
Author: User

I. Ajax stands for Asynchronous JavaScript and XML. Asynchronous is asynchronous, which is different from the synchronous method used in traditional web development.

II:About synchronous and asynchronous

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.

Specifically, asynchronous transmission divides bits into groups for transmission. Generally, each group is an 8-character group with a starting and ending bits at the header and tail of each group. It does not require the same receiver and sender clock during the transfer process, that is to say, the sender can send these groups at any time, and the receiver does not know when it will arrive. One of the most obvious examples is the communication between the computer keyboard and the host. Press the next key to send an 8-bit ASCII code to the host. The keyboard can send code at any time, this depends on the user input speed. The internal hardware must be able to receive a typed character at any time. This is a typical asynchronous transmission process. Asynchronous transmission has a potential problem, that is, the receiver does not know when the data will arrive. Before it detects the data and responds, the first bit has passed. This is like someone coming up to talk to you unexpectedly, but you didn't have time to respond and missed the first few words. Therefore, the information transmitted asynchronously starts with a starting bit and notifies the recipient that the data has arrived. This gives the recipient the time to respond, receive, and cache data bits; at the end of the transfer, a stop bit indicates the termination of the transfer information. By convention, idle (no data is transmitted) lines actually carry a Signal Representing Binary 1. The Start bit of the Step transmission changes the signal to 0, and other bits change the signal with the transmitted data information. Finally, the stop position changes the signal back to 1, and the signal remains till the next start position. For example, the number "1" on the keyboard, according to the 8-bit extended ASCII encoding, will send "00110001", at the same time need to add a start bit before the 8-bit, followed by a stop bit.

The bit groups for synchronous transmission are much larger. It does not send each character independently. Each character has its own Start and Stop bits, but sends them together. We call these combinations a data frame or frame for short.

The first part of a data frame contains a set of synchronization characters. It is a unique bit combination, similar to the Start bit mentioned earlier, used to notify the recipient that a frame has arrived, however, it can also ensure that the sampling speed of the receiver is consistent with the bit arrival speed, so that the receiving and receiving sides can synchronize.

The last part of a frame is a frame end mark. Like synchronization characters, it is also a unique Bit String, similar to the stop bit mentioned above, used to indicate that there is no data to be reached before the next frame starts.

Synchronous transmission is usually much faster than asynchronous transmission. The receiver does not have to start or stop each character. Once the frame synchronization characters are detected, it receives them when the next data arrives. In addition, the cost of synchronous transmission is also relatively small. For example, a typical frame may have 500 bytes (4000 bits) of data, which may only contain 100 bits of overhead. At this time, the added bit increases the total number of transmitted BITs by 2.5%, which is much smaller than the value-added value of 25% in asynchronous transmission. As the actual data bit in the data frame increases, the percentage of overhead bit will be reduced accordingly. However, the longer the bit length of the data, the larger the buffer required for caching the data, which limits the size of a frame. In addition, the larger the frame, the longer it occupies the continuous time of the transmitted media. In extreme cases, this will cause other users to wait too long.

III:

Ajax principles and XMLHttpRequest objects

The principle of AJAX is simply to use the XMLHTTPRequest object to send asynchronous requests to the server, obtain data from the server, and then use JavaScript to operate the Dom to update the page. The most critical step is to obtain request data from the server. To understand the process and principles, we must understand XMLHttpRequest.

XMLHttpRequest is the core mechanism of Ajax. It is first introduced in ie5. it is a technology that supports asynchronous requests. Simply put, JavaScript can promptly request and process responses to the server without blocking users. Achieve the effect of refreshing.

So let's start with XMLHttpRequest to see how it works.

First, let's take a look at the attributes of the XMLHTTPRequest object.

Its attributes include:

Onreadystatechange the event handler of the event triggered by each state change.

The string format of responsetext returned data from the server process.

Responsexml is a dom-compatible document data object returned by the server process.

Status Code returned from the server, such as common 404 (not found) and 200 (ready)

String information of the Status text accompanied by the status code

Readystate object status value

0 (not initialized) the object has been created, but has not been initialized (the open method has not been called)

1 (initialization) the object has been created and the send method has not been called

2 (send data) The send method has been called, but the current status and HTTP header are unknown.

3 (in data transmission) Some data has been received. Because the response and HTTP headers are incomplete, an error occurs when retrieving part of data through responsebody and responsetext,

4. After receiving the data, you can use responsexml and responsetext to obtain the complete response data.

Note: different browsers may require different methods to create an XMLHTTPRequest object. This difference is mainly reflected in IE and other browsers. The following is a standard method for creating an XMLHTTPRequest object.

Eg:

VaR XMLHTTP;
// Method for generating XMLHttpRequest objects for different browsers
Function getxmlhttp (){

// Create an XMLHTTPRequest object in IE

If (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}

// Create an XMLHTTPRequest object in a non-IE browser

Else if (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
}
}

 

Function sendparam (OBJ ){

If (! XMLHTTP ){
Alert ("An error occurred while creating the XMLHTTP object! ");
Return false;
}

Getxmlhttp ();

XMLHTTP. Open ("get", "check. php? User = "+ OBJ, true );

XMLHTTP. onreadystatechange = gettxt;

XMLHTTP. Send (null );

}

 

Function gettxt (){

If (XMLHTTP. readystate = 4 ){

If (XMLHTTP. Status = 200 ){

VaR sp = Document. getelementbyid ("warning ");

VaR flag = XMLHTTP. responsetext;

If (flag = "1 "){

Sp. innerhtml = "this user has been registered. Please enter another user name ";

Sp.style.css text = "color: red; font-size: 14px ";

} Else {

Sp. innerhtml = "registrable ";

Sp.style.css text = "color: green; font-size: 14px ";}

}

}

}

 

 

 

 

 

As shown above, the function first checks the overall state of XMLHttpRequest and ensures that it has been completed (readystatus = 4), that is, the data has been sent. Then, query the Request status based on the server settings. If everything is ready (status = 200), perform the following operations.

For the XMLHttpRequest methods, open and send, the open method specifies:

A. Type of data submitted to the server, that is, post or get.

B. request URL and transmitted parameters.

C. Transmission Mode. If the value is false, synchronization is performed. If the value is true, asynchronous transmission is performed. The default value is true. If it is an asynchronous communication method (true), the client will not wait for the server to respond; if it is a synchronous mode (false), the client will wait until the server returns a message before executing other operations. We need to specify the synchronization mode based on actual needs. In some pages, multiple requests may be sent, or even highly-intensive requests with organized and planned structures, the other one will overwrite the previous one. In this case, you must specify the synchronization mode.

The send method is used to send requests.

 

After learning about the XMLHttpRequest workflow, we can see that XMLHttpRequest is completely used to send a request to the server. Its role is also limited to this, but its role is the key to the entire Ajax implementation, because Ajax is nothing more than two processes, sending requests and responding to requests. And it is completely a client technology. XMLHttpRequest is so important because it handles the communication between the server and the client.

Now we can have a general understanding of the principles of Ajax. We can regard the server as a data interface, which returns a plain text stream. Of course, this text stream can be in XML format, HTML, or JavaScript code, it can also be a string. At this time, XMLHttpRequest requests this page from the server, and the server writes the text results to the page. This is the same as the normal Web development process, after the client asynchronously obtains this result, it is not directly displayed on the page, but processed by JavaScript first and then displayed on the page. As for many popular Ajax controls such as magicajax, other data types such as dataset can be returned, but the results encapsulated by this process are essentially no big difference.

 

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.