超时处理
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>超时处理</title>
<style>
#result{
width: 400px;
height: 200px;
border:solid 1px red;
}
</style>
</head>
<body>
<button>发送请求</button>
<div id="result">
<script>
//获取button元素,设置点击事件
const btn=document.getElementsByTagName('button')[0];
const result=document.querySelector("#result");
//绑定时间
btn.onclick=function(){
console.log("test");
//1、创建对象
const xhr=new XMLHttpRequest();
//超时2s设置,如果两秒没有返回结果,请求取消
xhr.timeout=2000;
//超时的回调
xhr.ontimeout=function(){
alert("网络异常,请稍后重试!!")
}
//网络异常回调
xhr.onerror=function(){
alert("你的网络好像出了一点问题!!")
}
//2、初始化,设置请求方法和url
//设置请求参数,在url后加?,多个参数之间使用&连接
//处理IE缓存问题,在url后添加
xhr.open('GET','http://127.0.0.1:8000/overTime-server');
//3、发送
xhr.send();
//4、事件绑定,处理服务端返回的结果
//on when 当...的时候
//readystate 是xhr对象中的属性 0 1 2 3 4
//change 改变
xhr.onreadystatechange=function(){
//判断服务端返回了所有的结果
if (xhr.readyState===4){
//判断响应的状态码 200 404 403 401 500
//2xx 表示成功
if (xhr.status>=200&&status<300){
//处理结果 行 头 空行 体
//响应行
// console.log(xhr.status);//状态码
// console.log(xhr.statusText);//状态字符串
// console.log(xhr.getAllResponseHeaders());//所有响应头
// console.log(xhr.response);//响应体
//设置result文本
result.innerHTML=xhr.response;
}else{
}
}
}
}
</script>
</div>
</body>
</html>
Server中
//超时处理
app.all('/overTime-server',(request,response)=>{
//设置响应头,设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//定时器
setTimeout(() => {
//设置简单的响应
response.send("ERROR OverTime");
}, 3000);
});
Ajax请求超时处理
最新推荐文章于 2024-03-29 02:23:45 发布