Home >Web Front-end >JS Tutorial >Ajax error handling methods

Ajax error handling methods

韦小宝
韦小宝Original
2017-12-30 17:38:472234browse

ajax How to solve the problem of status judgment if else statement when sending a request? Next, I will share with you how to deal with the errors ajax made through this article. Friends who are interested in ajax errors should take a look together

1 , There is a problem with the if else statement when ajax sends a request.

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 output xhr.responseText, the obtained content. It was very strange at the time. I wonder where these two 200 came from?

At that time, I tried to output a lot of content, but still could not find the reason. The problem was discovered only when the else statement was changed to console.log(xhr.readystate). At this time, the output check was 2, 3, and the obtained content was obtained. Only then did I discover the reason:

From when xhr sends a request to the end of the request, it will go through 5 states. The status codes are 0, 1, 2, 3, 4 (that is, the value of readystate). Each state Once a change occurs, the readystatechange event will be triggered and the event handling function will be called. When the status code changes to 2, it calls the readystatechange event, and then uses the if/else statement,

This is readystate, obviously not 4, and then uses the else statement to output 2. And so on, 3, At 4, the readystatechange event is called again. Only at 4, the content in the if is taken. The request is successful and the request content is returned.

The above is the method for handling Ajax errors introduced by the editor. I hope it will be helpful to everyone! !

Related recommendations:

ajax error debugging analysis in jQuery

##Examples to explain the basics of HTTP messages and ajax Knowledge

How Ajax implements website hijacking detection

The above is the detailed content of Ajax error handling methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn