// 超时设置 2s

xhr.timeout =2000;

// 超时回调

xhr.ontimeout = function(){

alert(‘网络异常,请稍后重试。’)

};

// 网络异常

xhr.onerror = function(){

alert(‘网络出问题。’)

};

以上代码放在new和open之间

//取消请求处理

xhr.abort();

如何解决重复发送请求,取消上一个请求

// 第一步:标识变量,是否在发送AJAX请求

let isSending = false;

btn.onclick = function(){

//第二步:进行判断,如果上一个正在发送,则取消该请求,创建一个新的请求

if (isSending) xhr.abort();

xhr = new XMLHttpRequest();

// 修改标识变量的值

isSending = true;

xhr.open(‘GET’,’http://127.0.0.1:8000/server’);

xhr.send();

xhr.onreadystatechange = function(){

if (xhr.readyState) {

// 修改标识变量

isSending = false;

}

};

};



版权声明:本文为weixin_61972561原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_61972561/article/details/131547640