JavaWeb前端-Ajax

简介

Asynchronous JavaScript And XML,异步的JavaScript和XML

XML:Extensible Markup Language,可扩展标记语言,是一种数据格式,可用来存储复杂的数据结构

Ajex作用:

  • 数据交换:可给服务器发送请求,获取服务器响应的数据
  • 异步交互:可在不重新加载整个页面 的情况下,与服务器交换数据并更新部分网页的技术

同步和异步

Axios

对原生Ajax进行了封装,简化书写
Axios官网

步骤:

  • 引入Axios的js文件
  • 使用Axios发送请求,并获取响应结果
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax-Axios</title>
</head>
<body>
    <input type="button" value="get" id="btnget">
    <input type="button" value="post" id="btnpost">

    <script src="js/axios.js">
    </script>
    <script>
        //1、get请求
        document.querySelector("#btnget").addEventListener("click",function(){
            //axios发起异步请求
            axios({
                method:"get",
                url:"http://127.0.0.1:3000/get",
            }).then((res) =>{ //成功回调函数
                console.log(res);
            }).catch((err) =>{ //失败回调函数
                console.log(err);
            })
        })
        //2、post请求
        document.querySelector("#btnpost").addEventListener("click",function(){
            //axios发起异步请求
            axios({
                method:"post",
                url:"http://127.0.0.1:3000/post",
                data:{username:"admin",password:"<PASSWORD>"},//post请求方式,请求体的数据
            }).then((res) =>{ //成功回调函数
                console.log(res);
            }).catch((err) =>{ //失败回调函数
                console.log(err);
            })
        })
    </script>
</body>
</html>

请求方式别名

格式:axios.请求方式(url [, data [, config]])

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax-Axios</title>
</head>
<body>
    <input type="button" value="get" id="btnget">
    <input type="button" value="post" id="btnpost">

    <script src="js/axios.js">
    </script>
    <script>
        //1、get请求
        document.querySelector("#btnget").addEventListener("click",function(){
            axios.get("http://127.0.0.1:3000/get").then((res) =>{ //成功回调函数
                console.log(res);
            }).catch((err) =>{ //失败回调函数
                console.log(err);
            })
        })
        //2、post请求
        document.querySelector("#btnpost").addEventListener("click",function(){
            axios.post("http://127.0.0.1:3000/post",{username:"admin",password:"<PASSWORD>"}).then((res) =>{ //成功回调函数
                console.log(res);
            }).catch((err) =>{ //失败回调函数
                console.log(err);
            })
        })
    </script>
</body>
</html>

async & await

可通过async和await把异步变为同步操作。async声明一个异步方法,await等待异步任务执行

前端向服务器端请求搜索数据的方法

html 复制代码
<script src="js/axios.js"></script>
    <script type="module">
        import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
        createApp({
            data() {
                return {
                    searchForm:{//封装用户输入的查询条件
                        name: '',
                        gender: '',
                        position: ''
                    },
                    empList: []
                }
            },
            methods: {
                async search(){
                    //发起Ajax请求,获取数据
                    // axios.get('http://localhost:8080/emps/list?name=${this.searchForm.name}&gender=${this.searchForm.gender}&position=${this.searchForm.position}').then(function (response) {
                    //     //请求成功,将数据保存到 empList 中
                    //     this.empList = response.data.data;
                    // });
                    let result = await axios.get('http://localhost:8080/emps/list?name=${this.searchForm.name}&gender=${this.searchForm.gender}&position=${this.searchForm.position}');
                    this.empList = result.data.data;
                },
                clear() {
                    //清空搜索条件
                    this.searchForm = {
                        name: '',
                        gender: '',
                        position: ''
                    }
                    this.search();
                }
            },
        }).mount('#container');
        </script>

await关键字只在async函数内有效,await关键字取代then函数,等待获取到请求成功的返回值

Vue生命周期

生命周期指一个对象从创建到销毁的整个过程

八个阶段:每触发一个生命周期事件,会自动执行一个生命周期方法(钩子方法)

html 复制代码
<script src="js/axios.js"></script>
    <script type="module">
        import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
        createApp({
            data() {
                return {
                    searchForm:{//封装用户输入的查询条件
                        name: '',
                        gender: '',
                        position: ''
                    },
                    empList: []
                }
            },
            methods: {
                async search(){
                    //发起Ajax请求,获取数据
                    // axios.get('http://localhost:8080/emps/list?name=${this.searchForm.name}&gender=${this.searchForm.gender}&position=${this.searchForm.position}').then(function (response) {
                    //     //请求成功,将数据保存到 empList 中
                    //     this.empList = response.data.data;
                    // });

                    let result = await axios.get('http://localhost:8080/emps/list?name=${this.searchForm.name}&gender=${this.searchForm.gender}&position=${this.searchForm.position}');
                    this.empList = result.data.data;
                },
                clear() {
                    //清空搜索条件
                    this.searchForm = {
                        name: '',
                        gender: '',
                        position: ''
                    }
                    this.search();
                }
            },
            //钩子函数
            mounted() {
                //页面加载时,自动执行一次查询
                this.search();
            }
        }).mount('#container');
    </script>
相关推荐
3秒一个大3 天前
Cookie/Session vs JWT 双 Token:登录认证方案的演进与对比
前端·安全·ajax
华科易迅3 天前
Vue通过Ajax获取后台路由信息
vue.js·ajax·okhttp
用户8113581881204 天前
【AJAX-Day2】Promise与回调地狱
前端·ajax
酉鬼女又兒9 天前
零基础快速入门前端蓝桥杯 Web 备考:AJAX 与 XMLHttpRequest 核心知识点及实战(可用于备赛蓝桥杯Web应用开发)
前端·ajax·职场和发展·蓝桥杯·css3·js
HP-Patience10 天前
【Python爬虫常见错误】- AJAX动态加载数据爬取
爬虫·python·ajax
Hello.Reader11 天前
Spark 4.0 新特性Python Data Source API 快速上手
python·ajax·spark
独断万古他化12 天前
【Java 实战项目】多用户网页版聊天室:消息传输模块 —— 基于 WebSocket 实现实时通信
java·spring boot·后端·websocket·ajax·mybatis
Hello.Reader13 天前
Spark Connect 快速入门远程连接 Spark 集群实战
javascript·ajax·spark
进击的雷神14 天前
攻克JSON接口分页与对象数组处理:基于AJAX数据源的精准博客爬虫设计
爬虫·ajax·json·spiderflow
gCode Teacher 格码致知16 天前
Javascript提高:Promise、Fetch、Axios、XHR、jQuery AJAX 完整对比-由Deepseek产生
javascript·ajax·jquery