AJAX——请求头、json、nodemon、网络异常、取消请求

73 篇文章 0 订阅
26 篇文章 0 订阅

AJAX

设置请求头信息

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>post</title>
    <style>
        #box {
            width: 200px;
            height: 100px;
            border-radius: 5px;
            border: 1px solid peru;
        }
    </style>
</head>

<body>
    <div id="box">

    </div>
    <script>
        const box = document.getElementById('box');
        box.addEventListener('mouseover', function() {
            // 创建对象
            const xhr = new XMLHttpRequest();
            // 初始化
            xhr.open('POST', 'http://127.0.0.1:8003/server');
            // 设置请求头,必须在open后面,send前面
            // 两个参数:名,值
            // Content-Type:预定义的,设置请求体内容的类型的,值是参数查询字符串的类型,是固定写法
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            // 也可以自定义设置名和值,对于自定义的报文,由于浏览器的安全机制,会报错,可以在接口那边设置(一般是后端人员设置)
            xhr.setRequestHeader('name', 'zs');
            // 发送
            // post请求的请求数据(请求体)是在send方法里面设置
            // 请求体内的参数格式可以设置任意格式,任意类型数据
            xhr.send('name:zs&age:22&sex:男');

            // 事件绑定,监听状态改变
            xhr.onreadystatechange = function() {
                // 判断服务端是否返回了全部结果
                if (xhr.readyState === 4) {
                    // 判断状态
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // 处理服务端返回的结果
                        box.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>

</html>

传送json格式数据

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            width: 200px;
            height: 100px;
            border-radius: 5px;
            border: 1px solid darkorange;
        }
    </style>
</head>

<body>
    <div id="box"></div>
    <script>
        const box = document.getElementById('box');
        window.onkeydown = function() {
            // 创建对象
            const xhr = new XMLHttpRequest();
            // 2.自动转换:设置响应体数据类型
            xhr.responseType = 'json';
            // 初始化
            xhr.open('GET', 'http://127.0.0.1:8003/jsonserver');
            // 发送
            xhr.send();
            // 绑定事件,监听对象状态的改变
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // 响应过来是数据是字符串类型的对象(json),所以要进行转换
                        // 1.手动对数据进行转化
                        /* let data = JSON.parse(xhr.response);
                        box.innerHTML = data.name; */
                        let data = xhr.response;
                        box.innerHTML = data.name;
                        console.log(xhr.response);
                    }
                }
            }
        }
    </script>
</body>

</html>

接口

// 引入express
const express = require('express');

// 创建应用对象
const app = express();
// 创建路由规则
// req:request,是对请求报文的封装
// res:response,是对响应报文的封装
app.get('/server', (req, res) => {
    // 设置响应头,设置允许跨域
    res.setHeader('Access-Control-Allow-Origin', '*');
    // 设置响应体
    res.send('hello,express!');
});
// all:可以接收任意类型的请求
app.all('/server', (req, res) => {
    // 设置响应头,设置允许跨域
    res.setHeader('Access-Control-Allow-Origin', '*');
    // *:所有类型的请求头信息都可以接受(有自定义请求头时)
    res.setHeader('Access-Control-Allow-Headers', '*');
    // 设置响应体
    res.send('hello,express!');
});
app.all('/jsonserver', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    // 响应的数据
    const data = {
        name: 'zs',
        sex: '男'
    };
    // 对对象进行字符串转换
    let str = JSON.stringify(data);
    // 设置响应体
    // send只能接收字符串和Buffer
    res.send(str);
});
// 设置监听端口
//访问路径:http://127.0.0.1:8003/server
app.listen(8003, () => {
    console.log('服务器已启动');
})

nodemon

自动重启node(服务器)

安装:

npm i -g nodemon

执行:

nodemon server.js

IE缓存问题

不支持ajax的实时重新加载

在路径后面加时间戳,每次发起的请求都不同

xhr.open('GET',‘http://127.0.0.1:8003/server?t='+Date.new())

请求超时和网络异常处理

app.all('/delay', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    setTimeout(() => {
        res.send('延时响应');
    }, 3000)
});
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>post</title>
    <style>
        #box {
            width: 200px;
            height: 100px;
            border-radius: 5px;
            border: 1px solid peru;
        }
    </style>
</head>

<body>
    <div id="box">

    </div>
    <script>
        const box = document.getElementById('box');
        box.addEventListener('click', function() {
            const xhr = new XMLHttpRequest();
            // 超时设置2s,超过2s请求没成功就取消
            xhr.timeout = 2000;
            // 设置超时回调
            xhr.ontimeout = function() {
                alert('网络异常,请稍后再试');
            };
            // 网络异常回调(断网,控制台的network,offline)
            xhr.onerror = function() {
                alert('网络异常');
            };
            xhr.open('POST', 'http://127.0.0.1:8003/delay');
            xhr.send();
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        box.innerHTML = xhr.response;
                    }
                }
            }
        })
    </script>
</body>

</html>

取消请求(有延迟效果的)

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>发送请求</button>
    <button>取消请求</button>
    <script>
        const btns = document.querySelectorAll('button');
        let xhr = null;
        btns[0].onclick = function() {
            xhr = new XMLHttpRequest();
            xhr.open('GET', 'http://127.0.0.1:8003/delay');
            xhr.send();
        };
        btns[1].onclick = function() {
            //调用abort()来取消请求
            xhr.abort();
        }
    </script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值