使用axios工具包,三种方法
- get请求
- post请求
- 使用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>axios发送Ajax请求</title> <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.24.0/axios.min.js"></script> </head> <body> <button>GET请求</button> <button>POST请求</button> <button>使用axios函数发送Ajax请求</button> <script> const btns = document.querySelectorAll('button'); //配置baseURL axios.defaults.baseURL = 'http://127.0.0.1:8000'; btns[0].onclick = function() { //GET请求 axios.get('/axios-server', { //url参数 params: { id: 1000, vip: 7 }, //请求头信息 headers: { name: 'axios', age: 20 } }).then(value => { console.log(value); }); } btns[1].onclick = function() { axios.post('/axios-server', { username: 'admin', password: 123 }, { //url params: { id: 200, vip: 150 }, //请求头参数 headers: { height: 112, wight: 113 } }).then(value => { console.log(value); }) } btns[2].onclick = function() { axios({ //请求方法 method: 'POST', //url url: '/axios-server', //url参数 params: { vip: 10, level: 30 }, //头信息 headers: { a: 100, b: 200 }, //请求参数 data: { username: 'admin', password: '123456' } }).then(value => { // console.log(value); console.log(value.status); console.log(value.statusText); console.log(value.headers); console.log(value.data); }) } </script> </body> </html>
点击每个按钮,便可在控制台看到服务器返回来的数据~