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

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>

在这里插入图片描述

作者:坚毅的小解同志原文地址:https://blog.csdn.net/m0_62360527/article/details/127834129

%s 个评论

要回复文章请先登录注册