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>
相关推荐
之歆19 天前
Ajax 基础技术深度解析:XHR 从入门到跨域
前端·ajax·okhttp
之歆19 天前
Ajax 进阶:跨域、CORS、JSONP 与请求封装实战
前端·javascript·ajax
sugar__salt19 天前
前端Ajax核心原理与实战:从异步机制到接口请求全解析
前端·javascript·ajax
YHHLAI19 天前
Ajax — 异步数据交互
ajax·okhttp·交互
meilindehuzi_a20 天前
深入理解 Ajax 异步请求:从 XMLHttpRequest 到 Node.js HTTP 服务实践
http·ajax·node.js
拾年27520 天前
从零手写 Ajax:用原生 XHR 搭建前后端交互全流程
前端·javascript·ajax
零壹AI实验室1 个月前
NVIDIA RTX Spark深度测评:个人AI智能体时代真的来了?
人工智能·ajax·spark
清水白石0081 个月前
Python 变量的本质:从“盒子思维”到“引用思维”,彻底理解赋值到底发生了什么
java·python·ajax
来恩10031 个月前
jQuery对Ajax的支持
前端·ajax·jquery