如何通过axios发起Ajax请求(最新推荐)

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

如何通过axios发起Ajax请求(最新推荐)

坚毅的小解同志   2022-11-19 我要评论

axios  

什么是axios

Axios是专注于网络数据请求的库,相比于原生的XMLHttpRequest对象,axios简单易用。相比于Jquery,axios更加轻量化,只专注于网络数据请求。

axios发起GET请求

axios发起get请求的语法:

在这里插入图片描述


代码

<body>
    <button id="btn1">发起get请求</button>
    <script>
        document.querySelector('#btn1').addEventListener('click', function () {
            let url = 'http://www.liulongbin.top:3006/api/get';
            axios.get(url, { params: { name: 'xiaoxie', age: '20' } }).then(function (res) {
                console.log(res.data);
            })
        })
    </script>
</body>

在这里插入图片描述

axios发起POST请求

axios发起post请求的语法

在这里插入图片描述

 <button id="btn2">发起post请求</button>
  document.querySelector('#btn2').addEventListener('click', function () {
            let url = 'http://www.liulongbin.top:3006/api/post';
            axios.post(url, { name: 'xiaoxie', age: '20' }).then(function (res) {
                console.log(res.data);
            })
        })

在这里插入图片描述

直接使用axios发起get请求

axios也提供了类似于Jquery中$.ajax()的函数,语法如下:

在这里插入图片描述

<body>
    <button id="btn3">发起ajax请求</button>
    <script>
        document.getElementById('btn3').addEventListener('click', function () {
            let url = 'http://www.liulongbin.top:3006/api/get';
            let paramsData = {
                name: 'xiaoxie',
                age: 20
            }
            axios({
                method: 'get',
                url: url,
                params: paramsData,
            }).then(
                function (res) {
                    console.log(res.data);
                }
            )
        })
    </script>
</body>

在这里插入图片描述

直接使用axios发起post请求

<body>
    <button id="btn4">发起ajax post请求</button>
        document.getElementById('btn4').addEventListener('click', function () {
            let url = 'http://www.liulongbin.top:3006/api/post';
            let paramsData = {
                name: 'xiaoxie',
                age: 20
            }
            axios({
                method: 'post',
                url: url,
                data: paramsData,
            }).then(
                function (res) {
                    console.log(res.data);
                }
            )
        })
    </script>
</body>

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们