First, fill in the Knowledge point:
ReadyState Status Code:
0: Request not initialized
1: Server Connection established
2: Request Accepted
3: In Request processing
4: The request is complete and the response is ready
HTTP Status Code:
200-Server successfully returned to Web page
404-The requested page does not exist
503-The server is temporarily unavailable
First in your own directory to establish a ajaxText.txt for testing, Ajax must be executed in the server, I am currently in the Apach local server test.
<! DOCTYPE html>Let btnrequest= document.getElementById (' btn '); Btnrequest.addeventlistener (' Click ', Load,false); functionload () {Let xhr=NewXMLHttpRequest (); Xhr.open (' GET ', ' ajaxTest.txt ',true); //two different ways to request Onload/onreadystatechangeXhr.onload=function() {Console.log (' OnLoad Status Code ${xhr.readystate} '); Console.log (' This is the text requested by the OnLoad function: ${ This. responsetext} '); } //callback the anonymous function after the state has changedXhr.onreadystatechange =function() {console.log (' onreadystatechange Status Code ${xhr.readystate} '); Console.log (' This is the text requested by the Onreadychange function: ${ This. responsetext} '); } xhr.send (); } </script> </body>Console
onReadyStateChange () is defined as a callback function whenever the returned status code is changed, and the onload only has a status code of 4 o'clock to callback the function.
This is the function that will be executed when the status code is 3 o'clock. OnProgress ().
When the server is normal, will basically return readystate status code 0~4, but not necessarily request data, so there is an HTTP status code to judge.
function () { if (xhr.readystate = = 4 && xhr.status = =) { console.log (' request succeeded and return data $ {this. responsetext} '); } }
The same is true in onload (), where the logic is written according to the situation.
<! DOCTYPE html>Let btnrequest= document.getElementById (' btn '); Btnrequest.addeventlistener (' Click ', Load,false); functionload () {Let xhr=NewXMLHttpRequest (); Xhr.open (' GET ', ' ajaxTest.txt ',true); //two different ways to request Onload/onreadystatechange //xhr.onload = function () {//if (xhr.status = =)// {//Console.log (' request succeeded and return data ${this.responsetext} ');// }//else{//Console.log (' unsuccessful request ');// }////Console.log (' OnLoad Status Code ${xhr.readystate} ');////Console.log (' This is the text requested by the OnLoad function: ${this.responsetext} ');// } //callback the anonymous function after the state has changedXhr.onreadystatechange =function(){ if(Xhr.readystate = = 4 && xhr.status = 200) {Let P= Document.createelement ("P"); P.innerhtml= This. responsetext; Document.body.appendChild (P); Console.log (' request succeeded and return data ${ This. responsetext} '); }} xhr.send (); } </script> </body>The difference between onload and Readychange in Ajax