借助xhr的一些属性和方法:

超时设置

1
xhr.timeout = 2000;

超时回调

1
2
3
xhr.ontimeout = function(){
alert("网络异常, 请稍后重试!!");
}

网络异常回调

1
2
3
xhr.onerror = function(){
alert("你的网络似乎出了一些问题!");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const xhr = new XMLHttpRequest();

//超时设置 2s 设置
xhr.timeout = 2000;
//超时回调
xhr.ontimeout = function(){
alert("网络异常, 请稍后重试!!");
}
//网络异常回调
xhr.onerror = function(){
alert("你的网络似乎出了一些问题!");
}

xhr.open("GET",'http://127.0.0.1:8000/delay');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status< 300){
result.innerHTML = xhr.response;
}
}
}

对它们的封装: —–传送门—–