1.用户给服务器发送强求,但服务器有时候不及时响应,或者存在网络异常等问题导致用户体验感下降,为了提高用户的体验感我们可以设置弹框提示
2.代码展示
<script>
const btn = document.getElementsByTagName('button')[0];
const result = document.getElementById('result');
const xhr = new XMLHttpRequest();
btn.addEventListener('click',function(){
//超时设置
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;
}
}
}
})
</script>
2.1 timeout属性等于一个整数,用来设置当请求发出后等待接受响应的时间。ontimeout()方法则是当等待超时后,自动执行的回调方法。
3.server.js
app.get('/delay',(request,response)=>{
//设置响应头 设置允许跨域,第二个参数‘*’指的是响应头内容
response.setHeader('Access-Control-Allow-Origin','*')
//设置响应
setTimeout(()=>{
response.send('hello AJAX delay')
},3000)
})