An actual example of w3school [1]:
<HTML> XMLHTTP. onreadystatechange = function () {If (XMLHTTP. readystate = 4 & XMLHTTP. status = 200) {document. getelementbyid ("mydiv "). innerhtml = XMLHTTP. responsetext ;}} XMLHTTP. open ("get", "/ajax/test1.txt", true); XMLHTTP. send ();} </SCRIPT>
Pay attention to the code order of the red part of the subscript. If you change the code to the following order:
<HTML> XMLHTTP. open ("get", "/ajax/test1.txt", true); XMLHTTP. send (); XMLHTTP. onreadystatechange = function () {If (XMLHTTP. readystate = 4 & XMLHTTP. status = 200) {document. getelementbyid ("mydiv "). innerhtml = XMLHTTP. responsetext ;}}} </SCRIPT>
<HTML> XMLHTTP. open ("get", "/ajax/test1.txt", true); XMLHTTP. onreadystatechange = function () {If (XMLHTTP. readystate = 4 & XMLHTTP. status = 200) {document. getelementbyid ("mydiv "). innerhtml = XMLHTTP. responsetext ;}} XMLHTTP. send ();} </SCRIPT>
Test results show that the execution results of the three code sequences are the same. This is because the following xhlhttp. onreadystatechange = Function
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }
It's just a function declaration (or registration) [In JS, it allows nested declaration of functions]. It just declares the onreadystatechange "attribute" (actually a function) of xhlhttp, not immediately executed. While
XMLHTTP. Open ("get", "/ajax/test1.txt", true); XMLHTTP. Send ();
Is executed immediately. If you want xhlhttp. onreadystatechange = function to be executed immediately, you only need to declare this module as "immediate execution ".
( xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }) ();
Reference
[1] http://www.w3school.com.cn/tiy/t.asp? F = ajax_async_true
Execution sequence of functions in Ajax