Ajax请求超时与网络异常处理图文详解(ajax请求异常是什么意思)干货分享

随心笔谈12个月前发布 admin
105 0


<!DOCTYPE html>
<html lang=”en”>

<head>
<meta charset=”UTF-8″ />
<titile>超时与网络异常处理</titile>
<style>
#content {
width: 400px;
height: 200px;
border: 1px solid rgb(4, 247, 25);
border-width: 3px;
margin: 20px 0 20px 0;
}
</style>
</head>

<body>
<button type=”button”>提交</button>
<div id=”content”></div>
<script>
const btn=document.getElementsByTagName(‘button’)[0];
const res=document.getElementById(‘content’);
btn.onclick=function() {

const xhr=new XMLHttpRequest();
xhr.timeout=2000;

xhr.ontimeout=function() {
alert(‘请求超时,请检查网络是否可用!’);
}

xhr.onerror=function() {
alert(‘你的网络开小差了,请重新连接网络试试’);
}

xhr.open(‘GET’, ‘http://127.0.0.1:8080/delay’);

xhr.send();

xhr.onreadystatechange=function() {
if (xhr.readyState===4) {
if (xhr.status >=200 && xhr.status < 300) {
res.innerHTML=xhr.response;
}
} else {

}
}
};
</script>
</body>

</html>

© 版权声明

相关文章