Ajax---错误处理

http状态码:
1、网络畅通,服务器端能接收到请求,服务器返回的结果不是预期结果。
可以判断服务器端返回的状态码,分别进行处理。xhr.status获取http状态码

2、网络畅通,服务器端没有接收到请求,返回404状态码
检查请求地址是否错误。

3、网络畅通,服务器端能接收请求,服务器端返回500状态码。
服务器端错误,找后端程序员进行沟通。

4、网络中断,请求无法发送到服务器端。
会触发xhr对象下面的onerror事件,在onerror事件处理函数中对错误进行处理。

Ajax状态码:表示Ajax请求的过程状态码,ajax对象返回的
Http状态码:表示请求的处理结果 是服务器端返回的

ajax错误处理

.html

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>07Ajax错误处理.html</title>
 6 </head>
 7 <body>
 8     <button id='btn'>发送Ajax请求</button>
 9     <script type="text/javascript">
10         var btn=document.getElementById('btn');
11         btn.onclick=function(){
12             var xhr=new XMLHttpRequest();
13             xhr.open('get','http://localhost:3000/error');
14             xhr.send();
15             xhr.onload=function(){
16                 //xhr.status 获取http状态码
17                 console.log(xhr.responseText)
18                 if(xhr.status==400){
19                     alert("请求出错!")
20                 }
21             }
22             xhr.onerror=function(){
23                 alert('网络中断,无法发送Ajax请求')
24             }
25         }
26     </script>
27 </body>
28 </html>

app.js

app.get('/error',(req,res)=>{
    res.status(400).send('not ok');
})

有网情况:

 无网情况:

posted @ 2020-04-21 08:51  codeing123  阅读(1753)  评论(0编辑  收藏  举报