XHR readystate
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 attributes of the XMLHttpRequest object:
Attributes | Description |
---|---|
onreadystatechange | Storage function (or function name), this function will be called whenever the readyState property changes. |
readyState | Stores the status of XMLHttpRequest. Changes from 0 to 4.
|
status | 200: "OK" 404: Page Not Found |
In the onreadystatechange event, we specify the tasks to be 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:
Instance
<html><!DOCTYPE html> <html> <head> <script> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","/try/ajax/ajax_info.txt",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>使用 AJAX 修改该文本内容</h2></div> <button type="button" onclick="loadXMLDoc()">修改内容</button> </body> </html>
Run instance »
Click the "Run Instance" button to view the online instance
Note: The onreadystatechange event is triggered 5 times (0 - 4), corresponding to each readyState Variety.
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):
Example
<!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("/try/ajax/ajax_info.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); } </script> </head> <body> <div id="myDiv"><h2>使用 AJAX 修改文本内容</h2></div> <button type="button" onclick="myFunction()">修改内容</button> </body> </html>
Run Instance»
Click the "Run Instance" button to view the online instance