一、下载安装

官网:https://github.com/axios/axios

二、使用

  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>TestAjax</title>
  6. <link crossorigin="anonymous" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.1/css/bootstrap.css" rel="stylesheet">
  7. <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.js"></script>
  8. <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.26.1/axios.js"></script>
  9. </head>
  10. <body>
  11. <div class="container">
  12. <h2 class="page-header">jQuery发送Ajax请求</h2>
  13. <button class="btn btn-primary">发送GET请求</button>
  14. <button class="btn btn-danger">发送POST请求</button>
  15. <button class="btn btn-info">发送通用(ALL)请求</button>
  16. </div>
  17. <script>
  18. const btns = document.querySelectorAll('button');
  19. axios.defaults.baseURL = 'http://localhost:8000',
  20. // get请求
  21. btns[0].onclick = function (){
  22. axios.get('/axios',{
  23. params: {
  24. id:100,
  25. vip:7,
  26. },
  27. headers: {
  28. name:'name',
  29. age:20,
  30. }
  31. }).then(value => {
  32. console.log(value);
  33. })
  34. }
  35. // post请求
  36. btns[1].onclick = function (){
  37. axios.post('/axios',{
  38. username : 'admin',
  39. password : 'admin'},
  40. {
  41. params: {
  42. id : 2
  43. },
  44. headers : {
  45. weight : 55
  46. }
  47. });
  48. }
  49. // 通用方法请求
  50. btns[2].onclick = function (){
  51. axios({
  52. method: 'POST',
  53. url: '/axios',
  54. params:{
  55. vip:9,
  56. },
  57. headers:{
  58. a:300
  59. },
  60. data:{
  61. user:'user'
  62. }
  63. });
  64. }
  65. </script>
  66. </body>
  67. </html>