How to handle Ajax errors
1. When ajax sends a request, the status determines if else statements.
var xhr = new XMLHttpRequest(); xhr.open("get",strUrl);<br><br>xhr.onreadystatechange = function(){ <br><br> if(xhr.readyState === 4){ <br><br><em id="__mceDel"> if(xhr.status ===200){ console.log(xhr.responseText); } <br><br></em><em style="line-height: 1.5;" id="__mceDel"><em id="__mceDel"><em id="__mceDel"><em id="__mceDel"> }else </em></em></em></em><em style="line-height: 1.5;" id="__mceDel"><em id="__mceDel"><em id="__mceDel"><em id="__mceDel"><em id="__mceDel">{<br> console.log(xhr.status); } <br> }</em></em></em></em></em>
xhr.send();
At that time, two 200 status codes were output, and then xhr. responseText was output. It was strange at the time. I don't know how these two 200 came from?
At that time, I tried to output a lot of content, but I still couldn't find the reason. The error is discovered only when the else statement is changed to console. log (xhr. readystate). At this time, the output result is 2 and 3 in sequence and the obtained content is obtained. Only then can we find the cause:
When xhr sends a request to the end of the request, the status code goes through five statuses: 0, 1, 2, 3, and 4 (that is, the value of readystate). The status changes every time, the readystatechange event is triggered and the event processing function is called. When the status code changes to 2, it calls the readystatechange event and then uses the if/else statement,
This is because readystate is obviously not 4, and then the else statement is used to Output 2. Similarly, when it is 3 or 4, the readystatechange event is called. Only when it is 4, the content in the if event is taken. The request is successful and the request content is returned.
The above section describes how to handle Ajax errors. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!