AJAX——重复请求、jquery、axios、fetch函数

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>Document</title>
</head>

<body>
    <button id="btn">发送请求</button>
    <script>
        const btn = document.getElementById('btn');
        // 请求标识符,为false时,说明请求结束,为true时,说明正在请求中
        let isSending = false;
        let xhr = null;
        btn.onclick = function() {
            // 先判断上一个请求是否完成,若还未完成,则取消上一个请求,重新开启一个请求,保证只存在一个请求
            if (isSending) xhr.abort();
            xhr = new XMLHttpRequest();
            isSending = true;
            xhr.open('GET', 'http://127.0.0.1:8003/delay');
            xhr.send();
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    isSending = false;
                }
            }
        }
    </script>

</body>

</html>

接口

app.all('/delay', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    setTimeout(() => {
        res.send('延时响应');
    }, 1000)
});
// 设置监听端口
//访问路径:http://127.0.0.1:8003/server
app.listen(8003, () => {
    console.log('使用nodemon服务器已启动');
})
jquery中的ajax

1.get请求

$.get(url,[data],[ccallback],[type])

url:请求的url地址;
data:请求携带的参数
callback:载入成功时的回调函数
type:设置返回内容格式,xml/html/script/json/text/_dedault

2.post请求

$.post(url,[data],[ccallback],[type])

url:请求的url地址;
data:请求携带的参数
callback:载入成功时的回调函数
type:设置返回内容格式,xml/html/script/json/text/_dedault

3.通用型请求

$.ajax({key:value,....})
<!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>
    <!-- <link rel="stylesheet" href="<link href=" https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap-grid.min.css " rel="stylesheet ">"> -->
    <!-- 在bootcdn找来的资源(src属性后面的东西) -->
    <!-- crossorigin="anonymous":向指定资源请求时,不会携带当前域名下的cookie -->
    <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

<body>
    <div class="container">
        <h2>jquery发送ajax请求</h2>
        <button>get</button>
        <button>post</button>
        <button>通用型</button>

    </div>
    <script>
        $('button').eq(0).click(function() {
            // get方式所传的数据可以在地址后面显示
            $.get('http://127.0.0.1:8003/jquery', {
                a: 100,
                b: 200
            }, function(data) {
                // 这个data是接口响应回来的数据
                console.log(data);
            }, 'json');
            // 设置了接受的内容是json类型的,就不用JSON.parse将传过来的字符串类型的数据转为json,会自动转换
        });
        $('button').eq(1).click(function() {
            $.post('http://127.0.0.1:8003/jquery', {
                a: 100,
                b: 200
            }, function(data) {
                console.log(data);
            });
            // 这里没设置内容类型,数据就是字符串类型的
        });
        // 通用型
        $('button').eq(2).click(function() {
            // 里面是一个对象
            $.ajax({
                // url
                url: 'http://127.0.0.1:8003/jquery',
                // 参数
                data: {
                    a: 100,
                    b: 200
                },
                // 请求类型
                type: 'GET',
                // 响应体类型
                dataType: 'json',
                // 成功的回调
                success: function(data) {
                    console.log(data);
                },
                // 失败的回调
                error: function() {
                    console.log('请求失败,请重试');
                },
                // 超时时间
                // timeout: 2000,
                // 头信息
                headers: {
                    c: 300,
                    d: 400
                }
            });
        })
    </script>
</body>

</html>

接口

app.all('/jquery', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');

    const obj = { name: 'zs', sex: '男' };
    res.send(JSON.stringify(obj));
});

axios发送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>Document</title>
//bootcdn
    <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
</head>

<body>
    <button>get</button>
    <button>post</button>
    <button>ajax</button>

    <script>
        // 配置baseUrl
        axios.defaults.baseURL = 'http://127.0.0.1:8003';
        const btns = document.querySelectorAll('button');
        // get
        btns[0].onclick = function() {
                // axios成功时不是调用回调,而是.then,返回的是一个promise
                axios.get('/axios', {
                    // url参数
                    params: {
                        id: 100,
                        nanme: '张三'
                    },
                    //请求头 
                    headers: {
                        name: 'xxx'
                    }
                }).then(function(data) {
                    console.log(data);
                })
            }
            // post
        btns[1].onclick = function() {
            // axios成功时不是调用回调,而是.then,返回的是一个promise
            // post请求的第一个参数是url,第二个参数是请求体,第三个参数是其他配置信息
            axios.post('/axios', {
                uername: 'zs',
                userpwd: '123456'
            }, {
                // url参数
                params: {
                    id: 100,
                    nanme: '张三'
                },
                // 请求头
                headers: {
                    name: 'xxx'
                },
            }).then(function(data) {
                console.log(data.data);
                console.log(data);
            })
        };
        // 通用方法
        btns[2].onclick = function() {
            // 返回一个对象
            axios({
                // 请求方式
                method: 'POST',
                // url
                url: '/axios',
                // url参数
                params: {
                    id: 100
                },
                // 请求头
                headers: {
                    a: 100,
                    b: 200
                },
                // 请求体参数
                data: {
                    name: '李四',
                    age: 22
                }
            }).then(res => {
                console.log(res.config);
            })
        }
    </script>
</body>

</html>

接口

app.all('/axios', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');

    const obj = { name: 'zs', sex: '男' };
    res.send(JSON.stringify(obj));
});
fetch函数

是属于全局对象,可以直接调用

<!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>
    <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
</head>

<body>
    <button>发送请求</button>
    <script>
        const btn = document.querySelector('button');
        btn.onclick = function() {
            // fetch函数返回的是一个promise对象,用.then的回调处理接收的数据
            // 如果要设置url参数,就直接写在uel后面,用?隔开
            fetch('http://127.0.0.1:8003/fetch?sex=boy', {
                // 请求方式
                method: "POST",
                // 请求头
                headers: {
                    name: 'zs'
                },
                // 请求体(如果是get请求就没有请求体这个配置项)
                body: 'name=zs&pwd=123456'
            }).then(res => {
                // .text()在__proto__里面
                // return res.text();
                // 将服务器传过来的数据转为json数据
                return res.json();
                console.log(res);
            }).then(res => {
                // 这里的res就是服务器响应过来的数据
                // console.log(JSON.parse(res));
                console.log(res);
            })
        }
    </script>
</body>

</html>

接口

app.all('/fetch', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');

    const obj = { name: 'zs', sex: '男' };
    res.send(JSON.stringify(obj));
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值