原因
在日常网站处理中,经常会遇到发送请求后一定时间内没有获得响应,前端显示未响应结果
后端controller
@RequestMapping(value = "/delay",method = RequestMethod.GET)
@ResponseBody
public String test05(HttpServletRequest req, HttpServletResponse resp) throws InterruptedException {
//设置响应头
resp.setHeader("Access-control-Allow-Origin","*");
//设置延时响应时间
TimeUnit.SECONDS.sleep(3);
return "延时响应";
}
前端页面
<html>
<head>
<title>请求超时和异常</title>
<style>
#result{
width: 200px;
height: 100px;
border: solid 1px #00ff00;
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
//获取元素对象
var btn = document.getElementsByTagName('button')[0];
var result = document.getElementById('result');
btn.addEventListener("click",function () {
//创建对象
var xhr = new XMLHttpRequest();
//设置两秒超时
xhr.timeout = 2000;
//超时回调
xhr.ontimeout = function(){
alert("网络异常,请稍后再试!")
};
//网络异常回调
xhr.onerror = function(){
alert("不好意思,您的网络似乎开了小差")
};
//初始化 设置类型和URL
//ie缓存问题,ie浏览器会将ajax返回值保存在本地缓存中,如果服务器改变,ie还是会优先调用本地缓存,导致交互性不够,
//想要解决ie缓存问题,就需要在请求后面加上时间参数保证不是同一次请求
// xhr.open('GET', 'http://127.0.0.1:8080/ie');
xhr.open('GET', 'http://127.0.0.1:8080/delay?time='+Date.now());
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4){
if (xhr.status >= 200 && xhr.status < 300){
result.innerHTML = xhr.response;
}
}
}
})
</script>
</body>
</html>
点击发送异步请求两秒后没有收到响应:
可以看到响应体中没有数据
同理,如果出现网络中断或其他异常现象,会执行js语句中的onerror方法。这里就不继续演示了,很简单,只需要将后端传输延时再设置长一点,前端发送请求后关闭服务器就可以实现。