Ajax XHR readyState


AJAX onreadystatechange incident

insert image description here

onreadystatechange event

When a request is sent to the server, we need to perform some tasks based on the response.

Whenever the readyState changes, the onreadystatechange event is fired.

The readyState attribute holds the state information of XMLHttpRequest.

The following are the three important properties of the XMLHttpRequest object:

Attributes describe
onreadystatechange Stores the function (or function name) that will be called whenever the readyState property changes.
readyState Holds the state of the XMLHttpRequest. Varies from 0 to 4.
0: request not initialized
1: server connection established
2: request received
3: request processing
4: request completed and response ready
status 200: “OK”
404: Page not found

In the onreadystatechange event, we specify what to do when the server response is ready to be processed.

When readyState is equal to 4 and the status is 200, the response is ready:

example

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }

Note: The onreadystatechange event is fired 5 times (0 - 4), corresponding to each change of readyState.

use callback function

A callback function is a function that is passed as an argument to another function.

If you have multiple AJAX tasks on your site, you should write a standard function for creating an XMLHttpRequest object and call that function for each AJAX task.

The function call should contain the URL and the task to perform when the onreadystatechange event occurs (may be different for each call):

example

function myFunction() {
    loadXMLDoc("/try/ajax/ajax_info.txt",
    function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
        }
    });
}

Guess you like

Origin blog.csdn.net/m0_62617719/article/details/130373065