取消上一次请求。(xhr对象上的about方法)

about 取消本次请求(拦截回来的响应)
let lastxhr;
 let btn = document.getElementById('btn');
btn.onclick = function () {
    if (lastXhr) {
        lastXhr.abort();
        // return;
    }
        lastXhr = getCode()
}

function getCode() {
    // 1.实例化XMLHttpRequest对象
    let xhr = new XMLHttpRequest();
    //  2.设置onreadystatechange监听
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.response);
        }
    }
    //  3.指定发送的方式,地址,携带的参数
    xhr.open('GET', 'http://localhost:3000/get_code');

    //  4.发送请求
    xhr.send();
    }
发布了29 篇原创文章 · 获赞 0 · 访问量 188

猜你喜欢

转载自blog.csdn.net/qq_41523392/article/details/103827916