在一个项目真正上线的时候,一定会存在一个项目超时的问题,也就是服务端无法及时响应客户端提交的内容。通过对ajax设置超时设置,给用户一个提醒。
在网路异常的时候也给用户一个提醒
超时和异常给用户一个提醒(通过ajax)
前端设置
<style>
#result {
width: 200px;
height: 200px;
border: solid seagreen 1px;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
服务端设置 这时候发送ajax请求会3s后收到响应
//1、导入express
const express=require('express')
//2、创建应用对象 创建web服务器
const app=express()
//3、创建路由规则
//监听客户端的GET请求和POST请求,并向客户端响应具体内容
//requset是对请求报文的封装
//response是对响应报文的封装
app.get('/timeout',function(requset,response){
//设置响应头 名称 值----设置允许跨域
response.setHeader('Access-Control-Allow-Origin','*');
//设置延时
setTimeout(()=>{
//设置响应体
response.send('延时效果');//3s之后返回给客户端
},3000)
})
//4、监听端口 启动服务
//启动服务器.lisen(端口号,(启动成功职之后的回调函数)) 端口号是80可以省略
app.listen(8000,()=>{
console.log('8000启动成功')
})
前端js部分
const btn=document.getElementsByTagName('button')[0];
const result=document.getElementById('result');
btn.addEventListener('click', function() {
//4步骤走
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8000/timeout');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status < 300 && xhr.status >= 200) {
result.innerHTML = xhr.response;
}
}
}
})
超时设置:时间定为3秒(2s之后如果没有返回结果 就发送超时设置)
const btn=document.getElementsByTagName('button')[0];
const result=document.getElementById('result');
btn.addEventListener('click', function() {
//4步骤走
const xhr = new XMLHttpRequest();
//超时设置 2s设置 两秒之内 消息没有 就请求取消
xhr.timeout=2000;
xhr.open('GET', 'http://127.0.0.1:8000/timeout');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status < 300 && xhr.status >= 200) {
result.innerHTML = xhr.response;
}
}
}
})
超时提醒(在实际场景会使用div 实际场景)
const btn=document.getElementsByTagName('button')[0];
const result=document.getElementById('result');
btn.addEventListener('click', function() {
//4步骤走
const xhr = new XMLHttpRequest();
//超时设置 2s设置 两秒之内 消息没有 就请求取消
xhr.timeout=2000;
//超时的回调
xhr.ontimeout=function(){
alert('网络异常,请稍后重试')
}
xhr.open('GET', 'http://127.0.0.1:8000/timeout');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status < 300 && xhr.status >= 200) {
result.innerHTML = xhr.response;
}
}
}
})
网络异常超时回调
//网络异常回调
xhr.onerror=function(){
alert('网络异常,请稍后重试')
}
可以借助chorme浏览器进行
在网络模块设置离线