jQuery和Axios发送AJAX请求

jQuery中AJAX方法

web服务器代码,优先写在前面后面通过jQuery方法直接访问

// 1.引入express模块
const express = require("express");
const app = express();

app.get('/get', (req, res) => {
    // 设置响应头 设置允许跨域
    res.setHeader('Access-Control-Allow-Origin', '*')
    //设置响应
    res.send('HELLO AJAX jQuery-GET请求~');
})
app.post('/post', (req, res) => {
    // 设置响应头 设置允许跨域
    res.setHeader('Access-Control-Allow-Origin', '*')
    //设置响应
    res.send('HELLO AJAX jQuery-POST请求~');
})
app.post('/delay', (req, res) => {
    // 设置响应头 设置允许跨域
    res.setHeader('Access-Control-Allow-Origin', '*')
    //设置响应
    res.send('HELLO AJAX jQuery-通用请求~');
})
app.listen(3000, () => {
    console.log("服务器运行在端口3000中~~~");
})

GET请求

  • 语法:
  • $.get(url, [data], [callback], [type])
    • 参数:
    • url:请求的URL地址
    • data:请求携带的参数
    • callback:载入成功时回调函数
    • type:设置返回内容格式:json, xml, html, script, text, _default

POST请求

  • 语法:
  • $.post(url, [data], [callback], [type])
    • 参数:
    • url:请求的URL地址
    • data:请求携带的参数
    • callback:载入成功时回调函数
    • type:设置返回内容格式:json, xml, html, script, text, _default

通用请求

  • 语法:
  • $.ajax({ })
  • url:“url”,data: {},type: ,dataType:‘json’,success: function () {},timeout: ,error: callback,header:
    • 参数是一个对象,对象中的属性有:
    • url:请求的URL地址
    • data:请求的参数
    • type:请求类型GET/POST请求方法等
    • dataType:设置返回内容格式:json, xml, html, script, text, _default
    • success:请求成功的回调函数
    • timeout:设置超时时间
    • error:失败后的回调函数
    • header:设置头信息
      三种方法请求的代码演示
      在这里插入图片描述
<!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/jquery/3.6.0/jquery.min.js"></script>
    <link crossorigin="anonymous" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.1/css/bootstrap.min.css"
        rel="stylesheet">
</head>

<body>
    <div class="container">
        <h2 class="page-header">jQuery发送AJAX请求</h2>
        <button class="btn btn-primary">GET</button>
        <button class="btn btn-danger">POST</button>
        <button class="btn btn-info">通用方法ajax</button>
    </div>
    <div class="container">

    </div>
    <script>
        $('button').eq(0).click(function () {
            $.get("http://127.0.0.1:3000/get", { a: 100, b: 200 }, function (data) {
                $("div").eq(1).html(data.text)
            }, 'json')
        })
        $('button').eq(1).click(function () {
            $.post("http://127.0.0.1:3000/post", { a: 100, b: 200 }, function (data) {
                $("div").eq(1).html(data.text)
            },'json')
        })
        $('button').eq(2).click(function () {
            $.ajax({
                // url
                url: "http://127.0.0.1:3000/delay",
                // 参数
                data: { a: 100, b: 200 },
                // 请求类型
                type: "post",
                // 响应体结果
                dataType: 'json',
                // 成功的回调函数
                success: function (data) {
                    $("div").eq(1).html(data.text)
                },
                // 超时时间
                timeout: 2000,
                // 错误回调函数
                error: function(){
                    console.log("出错了!!");
                },
            })
        })
    </script>
</body>

</html>

Axios发送AJAX请求

在node环境下需要安装axios,代码:
npm install axios
或者从CDN引入<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.24.0/axios.min.js"></script>
axios.defaults.baseURL可以配置一个整体的共同url部分

GET请求

  • 语法:
  • axios.get(url, [config])

POST请求

axios函数通用请求方法

  • 语法:
  • axios.post({config})
<body>
    <div class="container">
        <h2 class="page-header">Axios发送AJAX请求</h2>
        <button class="btn btn-primary">GET</button>
        <button class="btn btn-danger">POST</button>
        <button class="btn btn-danger">Axios</button>
    </div>
    <div class="container">

    </div>
    <script>
        let btn = document.getElementsByTagName('button')
        // 配置 baseURL
        axios.defaults.baseURL = 'http://127.0.0.1:3000';
        btn[0].onclick = function () {
            axios.get('/get', {
                // 参数
                params: {
                    id: 1001,
                    name: '江流'
                },
            }).then(response => {
                console.log(response.data);
            })
        }
        btn[1].onclick = function () {
            axios.post('/post', {
                // 请求体
                username: 'admin',
            }, {
                params: {
                    // 参数
                    id: 1001,
                    name: '江流'
                },
                // 设置头信息
                headers: {
                    name: "Axios"
                }
            }).then(response => {
                console.log(response.data);
            })
        }
        btn[2].onclick = function () {
            axios({
                method: 'POST',
                // 参数
                url: '/post',
                params: {
                    id: 1001,
                    name: '江流'
                },
                // 设置头信息
                headers: {
                    name: "Axios"
                },
                // 请求体参数
                data: {
                    username: 'admin'
                }
            }).then(response => {
                console.log(response.data);
            })
        }
    </script>
</body>

在这里插入图片描述

fetch()函数发送AJAX请求

  • WorkerOrGlobalScope.fetch()是一个全局方法,可以直接调用
  • 语法:
  • fetch(input[, init]);
    • 参数:
    • input:包含要获取资源的 URL的字符串
    • init可选参数,是相关配置对象
    <script>
        let btn = document.getElementsByTagName('button')
        // 配置 baseURL
        btn[0].onclick = function () {
            fetch('http://127.0.0.1:3000/get?id=100', {
                // 请求方法
                method: 'get',
                // 请求头
                headers: {
                    name: 'fetch'
                },
            }).then(response=>{
                console.log(response);
                return response.text();
                //return response.josn(); 如果是json格式就调用这个方法
            }).then(response=>{
                console.log(response);
            })
        };

        btn[1].onclick = function () {
            fetch('http://127.0.0.1:3000/post?id=100', {
                // 请求方法
                method: 'post',
                // 请求头
                headers: {
                    name: 'fetch'
                },
                // 请求体
                body: 'username=admin'
            }).then(response=>{
                console.log(response);
                return response.text();
                //return response.josn(); 如果是json格式就调用这个方法
            }).then(response=>{
                console.log(response);
            })
        };

    </script>

在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值