Ajax working principle and example explanation

1. What is AJAX

  AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML), the biggest role of AJAX is to automatically update part of the content without reloading the entire page by exchanging data with the server. Traditional web pages (without AJAX) require reloading the entire web page if the content needs to be updated.

2. XMLHttpRequest object

  XMLHttpRequest is the basis of AJAX. XMLHttpRequest is used to exchange data with the server. XMLHttpRequest has a compatibility problem. Old versions of Internet Explorer (IE5 and IE6) use ActiveX objects, and other versions use XMLHttpRequest objects. Specific examples are,

var xhr = null;

try {
xhr = new XMLHttpRequest();
} catch (e) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}

3. Send a request to the server

To send the request to the server, we use the open() and send() methods of the XMLHttpRequest object:

xhr.open(method,url,async);
xhr.send();
 
Method's get and post comparison

GET is simpler and faster than POST, and works in most cases.

However, use a POST request in the following cases:

  • Unable to use cache file (update file or database on server)
  • Send large amounts of data to the server (POST has no data limit)
  • POST is more stable and reliable than GET when sending user input containing unknown characters

get实例:(1)xhr.open("GET","test.php",true); xhr.send();

     (2) xhr.open("GET","test.php?a=1&b=2",true); xhr.send();

post实例:(1)xhr.oprn("POST","test.php",true);xhr.send();

     (2)xhr.oprn("POST","test.php",true);xhr.send();// To send data to the background, please use setRequestHeader() to add HTTP header. Then specify the data you wish to send in the send() method:

      xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

      xhr.send("a=1&b=2");

Asynchronous and synchronous (async true and false)
If the XMLHttpRequest object is to be used with AJAX, the async parameter of its open() method must be set to true,

The difference between asynchronous transmission and synchronous transmission
Asynchronous transmission is character-oriented transmission, and its unit is character; while synchronous transmission is bit-oriented transmission, and its unit is frame, when it transmits, it requires the receiver and the sender's clock to keep consistent.
Specifically, asynchronous transmission divides bits into small groups for transmission. Generally, each group is an 8-bit character, and there is a start bit and a stop bit at the head and tail of each group. During the transmission process, the clocks of the receiver and the sender are not required to be consistent, that is, to send The party can send these groups at any moment, and the receiver does not know when it arrives. One of the most obvious examples is the communication between the computer keyboard and the host computer. When a key is pressed, an 8-bit ASCII code is sent to the host computer. The keyboard can send the code at any time, depending on the user's input speed. The internal hardware must be A typed character can be received at any time. This is a typical asynchronous transfer process. A potential problem with asynchronous transfers is that the receiver does not know when the data will arrive. The first bit has passed before it can detect the data and respond. It's like someone unexpectedly comes up from behind to talk to you, and you miss the first few words before you can react. Therefore, each asynchronous transfer begins with a start bit, which informs the receiver that data has arrived, which gives the receiver time to respond, receive, and buffer bits of data; at the end of the transfer, a stop bit indicates Termination of this transmission. By convention, lines that are idle (not carrying data) actually carry a signal representing a binary 1. The start bit of the step transmission makes the signal become 0, and the other bits make the signal change with the transmitted data information. Finally, the stop bit causes the signal to change back to 1, which remains until the next start bit arrives. For example, the number "1" on the keyboard will send "00110001" according to the 8-bit extended ASCII encoding. At the same time, a start bit and a stop bit should be added in front of the 8-bit bit.
The packet of bits transmitted synchronously is much larger. Instead of sending each character independently, each with its own start and stop bits, it combines them and sends them together. We call these combinations data frames, or simply frames.
The first part of the data frame contains a set of sync characters, which is a unique combination of bits, similar to the start bit mentioned earlier, used to notify the receiver that a frame has arrived, but it also ensures the receiver's sampling speed It is consistent with the arrival speed of the bit, so that the sender and the receiver are synchronized.
The last part of the frame is an end-of-frame marker. Like the sync character, it is a unique string of bits, similar to the stop bit mentioned earlier, used to indicate that there is no more incoming data until the next frame begins.
  Isochronous transfers are generally much faster than asynchronous transfers. The receiver does not have to start and stop each character. Once frame sync characters are detected, it receives them as the next data arrives. In addition, the overhead of isochronous transmission is relatively small. For example, a typical frame might have 500 bytes (ie 4000 bits) of data, which might contain only 100 bits of overhead. At this time, the additional bits increase the total number of bits transmitted by 2.5%, which is much smaller than the 25% increase in asynchronous transmission. As the actual data bits in the data frame increase, the percentage of overhead bits will decrease accordingly. However, the longer the data bits, the larger the buffer required to cache the data, which limits the size of a frame. In addition, the larger the frame, the longer the continuous time it occupies the transmission medium. In extreme cases, this will cause other users to wait too long.
After understanding the concepts of synchronization and asynchrony, you should have a clearer understanding of why ajax can improve the user experience. It uses the asynchronous request method. For example, if the community where you live is facing water outage due to certain circumstances, the relevant departments have announced two plans. One is to completely cut off water for 8 hours. returned to normal after an hour. The second is that the water is not completely cut off for 10 hours. The water is not completely cut off during these 10 hours, but the flow is much smaller than the original. After 10 hours, the flow returns to normal. So, if it is you, which method would you choose? ? Obviously the latter.

4. Server response

  To get a response from the server, use the responseText or responseXML properties of the XMLHttpRequest object. If the response from the server is not XML, use the responseText property.
The responseText property returns the response as a string, so you can use it like this:
Example: document.getElementById("myDiv").innerHTML=xhr.responseText;

If you need json format, you can use JSON.parse to convert.

5.onreadystatechange event
When the request is sent to the server, we need to perform some response-based tasks.
The onreadystatechange event is fired whenever readyState changes.
The readyState property holds the state information of the XMLHttpRequest.
Here are three important properties of the XMLHttpRequest object:

Example: xhr . onreadystatechange = function ( ) {

     if(xhr.readyState==4 && xmlhttp.status==200){

      document.getElementById("myDiv").innerHTML=xhr.responseText; }

    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325000783&siteId=291194637