原生ajax 手动取消请求

210 阅读1分钟

原生ajax 手动取消请求

<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta name="generator" content="editplus" />
    <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
    <meta charset="UTF-8">
    <title>手动取消请求</title>

</head>

<body>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: 1px solid #3d3c07
        }
    </style>

    <button>点击发送</button>
    <button>点击取消</button>
    <div id="result"></div>

    <script>
        //获取元素对象
        const bten = document.querySelectorAll('button')
            //获取元素对象
        const res = document.getElementById("result")
            //创建对象
        const xhr = new XMLHttpRequest()
            //发送请求
        bten[0].onclick = function() {
            //初始化对象
            xhr.open('POST', 'http://127.0.0.1:8000/ser')
                //发送对象
            xhr.send(12312313131)
            console.log("发送请求")


            xhr.onreadystatechange = function() {
                //判断服务端返回了所有的结果全部数据
                if (xhr.readyState === 4) {
                    //判断响应状态码 200 404 403 401 500 200到300的
                    if (xhr.status >= 200 && xhr.status < 300) { //处理结果 行 头 空行 体 console.log(xhr.status); //响应行 状态码
                        console.log(xhr.statusText); //响应状态说明 console.log(xhr.getAllResponseHeaders); //响应头
                        console.log(xhr.response); //响应体
                        res.innerHTML = xhr.response
                    } else {}
                }
            }

        }

        //取消请求 abort
        bten[1].onclick = function() {
            //取消请求
            xhr.abort()
            console.log("取消请求")

        }
    </script>
</body>

</html>