Ajax的错误处理
- 网络畅通,服务器端能接收到请求,服务器端返回的结果不是预期结果。
可以判断服务器端返回的状态码,分别进行处理。xhr.status 获取http状态码
html:
<body>
<button id="btn">发送ajax请求</button>
</body>
<script>
var btn = document.querySelector('#btn')
btn.onclick = (() => {
//1.创建ajax对象
var xhr = new XMLHttpRequest()
//2.告诉ajax对象要向哪里发送请求,以什么方式发送请求
//请求方式,请求地址
xhr.open('get','http://localhost:3000/error')
//3.发送请求
xhr.send();
//4.responseText是获取服务器端响应到客户端的数据
xhr.onload = () => {
//xhr.status获取状态码 通过状态码对不同错误分别进行处理
console.log(xhr.responseText);
console.log(xhr.status);
if(xhr.status == 400) {
console.log('请求出错');
}
}
})
</script>
app.js
//07-错误处理
app.get('/error',(req,res) => {
res.status(400).send('error!')
})
-
网络畅通,服务器端没有接收到请求,返回404状态码。
检查请求地址是否错误。
错误效果:
-
网络畅通,服务器端能接收到请求,服务器端返回500状态码。
服务器端错误,找后端程序员进行沟通。
-
网络中断,请求无法发送到服务器端。
会触发xhr对象下面的onerror事件,在onerror事件处理函数中对错误进行处理。
模拟断网,刷新页面后将network设置为offline
var btn = document.querySelector('#btn')
btn.onclick = (() => {
//1.创建ajax对象
var xhr = new XMLHttpRequest()
//2.告诉ajax对象要向哪里发送请求,以什么方式发送请求
//请求方式,请求地址
xhr.open('get','http://localhost:3000/error')
//3.发送请求
xhr.send();
//4.responseText是获取服务器端响应到客户端的数据
xhr.onload = () => {
//xhr.status获取状态码 通过状态码对不同错误分别进行处理
console.log(xhr.responseText);
console.log(xhr.status);
if(xhr.status == 400) {
console.log('请求出错');
}
}
//当网络中断时会触发onerror事件
xhr.onerror = (() => {
alert('网络中断,无法发送ajax请求')
})
})
区分ajax状态码和http状态码
- Ajax状态码:表示Ajax请求的过程状态ajax对象返回的
- Http状态码:表示请求的处理结果 是服务端返回的