Ajax---错误处理
http状态码:
1、网络畅通,服务器端能接收到请求,服务器返回的结果不是预期结果。
可以判断服务器端返回的状态码,分别进行处理。xhr.status获取http状态码
2、网络畅通,服务器端没有接收到请求,返回404状态码
检查请求地址是否错误。
3、网络畅通,服务器端能接收请求,服务器端返回500状态码。
服务器端错误,找后端程序员进行沟通。
4、网络中断,请求无法发送到服务器端。
会触发xhr对象下面的onerror事件,在onerror事件处理函数中对错误进行处理。
Ajax状态码:表示Ajax请求的过程状态码,ajax对象返回的
Http状态码:表示请求的处理结果 是服务器端返回的
ajax错误处理
.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>07Ajax错误处理.html</title>
</head>
<body>
<button id=‘btn‘>发送Ajax请求</button>
<script type="text/javascript">
var btn=document.getElementById(‘btn‘);
btn.onclick=function(){
var xhr=new XMLHttpRequest();
xhr.open(‘get‘,‘http://localhost:3000/error‘);
xhr.send();
xhr.onload=function(){
//xhr.status 获取http状态码
console.log(xhr.responseText)
if(xhr.status==400){
alert("请求出错!")
}
}
xhr.onerror=function(){
alert(‘网络中断,无法发送Ajax请求‘)
}
}
</script>
</body>
</html>app.js
app.get(‘/error‘,(req,res)=>{
res.status(400).send(‘not ok‘);
})有网情况:

无网情况:
