1. 请求超时与网络异常
xhr.timeout = 2000;
xhr.ontimeout = function(){
alert("网络请求超时")
}
2. 取消请求
<button>发送</button>
<button>取消</button>
const btn = document.getElementsByTagName('button');
let xhr = null;
btn[0].onclick = function(){
var xhr = new XMLHttpRequest();
xhr.open("GET",'http://127.0.0.1:8000/deplay');
xhr.send();
};
btn[1].onclick = function(){
xhr.abort();
}
3. 重复请求问题
<body>
<button>发送</button>
<script>
const btn = document.getElementsByTagName('button');
let x = null;
let isSending = false;
btn[0].onclick = function(){
if(isSending) x.abort();
x = new XMLHttpRequest();
isSending = true;
x.open("GET",'http://127.0.0.1:8000/deplay');
x.send();
x.onreadystatechange = function(){
if(x.readyState === 4){
isSending = false;
}
}
};
</script>
</body>