309 Ajax 错误处理:非200,404,500,网络中断

	Ajax状态码: 表示Ajax请求的过程状态,ajax对象返回的
	Http状态码: 表示请求的处理结果,服务器端返回的



app.get('/error', (req, res) => {
    // console.log(abc);
    res.status(400).send('not ok');
});

07.Ajax错误处理.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <button id="btn">发送Ajax请求</button>
    <script type="text/javascript">
        var btn = document.getElementById('btn');

        btn.onclick = function() {
            // 1.创建ajax对象
            var xhr = new XMLHttpRequest();
            // 2.告诉Ajax对象要向哪发送请求,以什么方式发送请求
            // 1)请求方式 2)请求地址
            xhr.open('get', 'http://localhost:3000/error');
            // 3.发送请求
            xhr.send();
            // 4.获取服务器端响应到客户端的数据
            xhr.onload = function() {
                // xhr.status 获取http状态码
                console.log(xhr.responseText);

                if (xhr.status == 400) {
                    alert('请求出错')
                }
            }

            // 当网络中断时会触发onerrr事件
            xhr.onerror = function() {
                alert('网络中断, 无法发送Ajax请求')
            }
        }

        // Ajax状态码: 表示Ajax请求的过程状态 ajax对象返回的
        // Http状态码: 表示请求的处理结果 是服务器端返回的
    </script>
</body>

</html>

posted on 2020-02-21 22:04  冲啊!  阅读(410)  评论(0编辑  收藏  举报

导航