当前位置:   article > 正文

axios发送AJAX请求_axios $request->ajax()

axios $request->ajax()

效果展示:

功能:

点击GET按钮,发送get请求;

点击POST按钮,发送post请求;

点击AJAX按钮,使用axios函数发送请求。

代码如下:

HTML:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>ajax axios发送请求</title>
  8. <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
  9. <link crossorigin="anonymous" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu">
  10. <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.26.0/axios.js"></script>
  11. </head>
  12. <body>
  13. <div class="container">
  14. <h2 class="page-header">axios发送AJAX请求</h2>
  15. <button type="button" class="btn btn-primary">GET</button>
  16. <button type="button" class="btn btn-danger">POST</button>
  17. <button type="button" class="btn btn-info">AJAX</button>
  18. </div>
  19. <script>
  20. btn = document.querySelectorAll('button');
  21. // 配置baseURL
  22. axios.defaults.baseURL = 'http:127.0.0.1:8000';
  23. btn[0].onclick = function(){
  24. axios.get('/axios-server',{
  25. // url参数
  26. params: {
  27. name: 'xx',
  28. age: 20
  29. },
  30. // 请求头信息
  31. headers: {
  32. size: 123
  33. }
  34. }).then(value => {
  35. console.log(value);
  36. });
  37. };
  38. btn[1].onclick = function(){
  39. axios.post('/axios-server',{
  40. uname: 'admin'
  41. },{
  42. params: {
  43. id: 200
  44. },
  45. // 请求头参数
  46. headers: {
  47. height: 100,
  48. weight: 20
  49. }
  50. }).then(value => {
  51. console.log(value);
  52. })
  53. };
  54. btn[2].onclick = function(){
  55. axios({
  56. method: 'POST',
  57. url: '/axios-server',
  58. params: {
  59. vip: 11
  60. },
  61. headers: {
  62. a: 100,
  63. b: 30
  64. },
  65. data: {
  66. uname: 'admin'
  67. }
  68. }).then(response => {
  69. console.log(response.status);
  70. console.log(response.statusText);
  71. console.log(response.headers);
  72. console.log(response.data);
  73. })
  74. }
  75. </script>
  76. </body>
  77. </html>

JS:

  1. // 引入
  2. const { request } = require('express');
  3. // 创建应用对象
  4. const express = require('express');
  5. // 创建应用对象
  6. const app = express();
  7. // 创建路由规则
  8. app.all('/axios-server',(request,response) => {
  9. // 设置响应头 设置允许跨域
  10. response.setHeader('Access-Control-Allow-Origin','*');
  11. response.setHeader('Access-Control-Allow-Headers','*');
  12. const data = {name: 'xxx'};
  13. // 设置响应体
  14. response.send(JSON.stringify(data));
  15. });
  16. // 监听端口启动服务
  17. app.listen(8000,() => {
  18. console.log("服务已启动,8000端口监听中...");
  19. })

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/578817
推荐阅读
相关标签
  

闽ICP备14008679号