【Ajax】如何通过axios发起Ajax请求
•
前端

✍️ 作者简介: 前端新手学习中。
💂 作者主页: 作者主页查看更多前端教学
🎓 专栏分享:css重难点教学 Node.js教学 从头开始学习 ajax学习
文章目录
- axios
-
- 什么是axios
- axios发起GET请求
- axios发起POST请求
- 直接使用axios发起get请求
- 直接使用axios发起post请求
axios
什么是axios
Axios是专注于网络数据请求的库,相比于原生的XMLHttpRequest对象,axios简单易用。相比于Jquery,axios更加轻量化,只专注于网络数据请求。
axios发起GET请求
axios发起get请求的语法:

代码
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);
})
})

axios发起POST请求
axios发起post请求的语法

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()的函数,语法如下:

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);
}
)
})

直接使用axios发起post请求
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);
}
)
})

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/55a0854749.html
