AJAX - onreadystatechange event

onreadystatechange event

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

Whenever readyState changes, the onreadystatechange event will be triggered.

The readyState attribute stores the status information of XMLHttpRequest.

The following are three important properties of the XMLHttpRequest object:

Attributes                                       Description

onreadystatechange Stores a function (or function name) that will be called whenever the readyState property changes. ​

readyState ​ The state of XMLHttpRequest exists. Changes from 0 to 4.

                       0: The request is not initialized                                                                                                                                           ​ ​ ​ ​ 3: Request is being processed

                4: The request has been completed and the response is ready

status 200: "OK" 404: Page not found

In the onreadystatechange event, we stipulate Tasks performed when the server response is ready to be processed.

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

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

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

Using callback functions

A callback function is a function that is passed to another function in the form of parameters.

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

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

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

Continuing Learning
||
<!DOCTYPE html> <html> <head> <script> var xmlhttp; function loadXMLDoc(url,cfunc) { if (window.XMLHttpRequest) {// IE7+, Firefox, Chrome, Opera, Safari 代码 xmlhttp=new XMLHttpRequest(); } else {// IE6, IE5 代码 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=cfunc; xmlhttp.open("GET",url,true); xmlhttp.send(); } function myFunction() { loadXMLDoc("/asset/demo.ajax.php?dm=txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); } </script> </head> <body> <div id="myDiv"><h2>修改文本内容</h2></div> <button type="button" onclick="myFunction()">点击</button> </body> </html>
submitReset Code