<script>
const btn = document.getElementsByTagName("button")[0];
const box = document.querySelector("#box");
btn.onclick = function () {
//1、创建对象
const xhr = new XMLHttpRequest();
//网络超时设置,超时2s则取消发送
xhr.timeout = 2000;
//超时回调函数
xhr.ontimeout = function () {
alert("请求超时");
};
//网络异常回调、
xhr.onerror = function () {
alert("网络异常");
};
//2、初始化
//解决ie缓存问题
xhr.open("GET", "http://127.0.0.1:8000/delay");
//3、发送
xhr.send();
//4、事件绑定,处理服务端返回的结果
xhr.onreadystatechange = function () {
//判断(服务端返回了所有结果)
if (xhr.readyState === 4) {
//判断响应状态码 2##表示成功
if (xhr.status >= 200 && xhr.status < 300) {
box.innerHTML = xhr.response;
} else {
}
}
};
};
</script>
722_ajax_网络请求超时
- 本文链接: http://lzkpersonal.com.cn/2023/07/22/722-ajax-网络请求超时/
- 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!