Ajax的定義
Ajax(Asynchronous JavaScript and XML)是一種用于創建異步 Web 應用的技術,允許網頁在不重新加載整個頁面的情況下與服務器交換數據并更新部分內容。
Ajax的核心特點
異步通信:通過后臺與服務器交互,用戶操作不受干擾。
局部刷新:僅更新頁面特定部分,提升用戶體驗。
技術組合:依賴 JavaScript、XML(或 JSON)、HTML/CSS 和 XMLHttpRequest 對象。? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
異步交互:可以在不重新加載整個頁面的情況下,與服務器交換數據并更新部分網頁的技術。
如上圖,輸入文字,瀏覽器根據文字給出對應的推薦內容,這就是一種異步交互。
同步請求的過程如下圖
異步請求的過程如下圖
Axios
使用原生的Ajax請求的代碼編寫起來還是比較繁瑣的,所以接下來我們學習一門更加簡單的發送Ajax請求的技術Axios 。Axios是對原生的AJAX進行封裝,簡化書寫。Axios官網是:https://www.axios-http.cn
一、引入Axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
也可以下載一個axios的js文件放在目錄中引用
入門程序
點擊按鈕時,使用Axios發送請求
<!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>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>//發送GET請求document.querySelector('#btnGet').addEventListener('click', () => {//axios發起異步請求axios({url:'https://mock.apifox.cn/m1/3083103-0-default/emps/list',method:'GET'}).then((result)=>{console.log(result.data);//成功回調函數}).catch((error)=>{console.log(error);//失敗回調函數`})})//發送POST請求document.querySelector('#btnPost').addEventListener('click', () => {axios({url:'https://mock.apifox.cn/m1/3083103-0-default/emps/update',method:'POST'}).then((result)=>{console.log(result.data);//成功回調函數}).catch((error)=>{console.log(error);//失敗回調函數`})})</script>
</body>
</html>
以下有個小程序可以凸顯出axios的異步請求的特點
<!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>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>//發送GET請求document.querySelector('#btnGet').addEventListener('click', () => {axios.get('https://mock.apifox.cn/m1/3083103-0-default/emps/list').then((result) => {console.log(result.data);})//異步輸出(異步請求,此處不需要等待服務器,因此更快)console.log('異步輸出');})//發送POST請求document.querySelector('#btnPost').addEventListener('click', () => {axios.post('https://mock.apifox.cn/m1/3083103-0-default/emps/update',id='1').then((result) => {console.log(result.data);}).catch((err) => {});})</script>
</body>
</html>
當按下獲取數據GET按鈕時,axios的get方法啟用,然后程序繼續往下走,往控制欄里輸出‘異步輸出’,然后get方法獲取到服務器端的數據,輸出對應數據。
Vue的生命周期
vue的生命周期:指的是vue對象從創建到銷毀的過程。
vue的生命周期包含8個階段:每觸發一個生命周期事件,會自動執行一個生命周期方法,這些生命周期方法也被稱為鉤子方法。其完整的生命周期如下圖所示:
狀態 | 階段周期 |
beforeCreate | 創建前 |
created | 創建后 |
beforeMount | 掛載前 |
mounted | 掛載完成 |
beforeUpdate | 更新前 |
updated | 更新后 |
beforeDestroy | 銷毀前 |
destroyed | 銷毀后 |
其中我們需要重點關注的是mounted,其他的我們了解即可。
mounted:掛載完成,Vue初始化成功,HTML頁面渲染成功。以后我們一般用于頁面初始化自動的ajax請求后臺數據
案例
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Tlias智能學習輔助系統</title><style>/* 導航欄樣式 */.navbar {background-color: #b5b3b3; /* 灰色背景 */display: flex; /* flex彈性布局 */justify-content: space-between; /* 左右對齊 */padding: 10px; /* 內邊距 */align-items: center; /* 垂直居中 */}.navbar h1 {margin: 0; /* 移除默認的上下外邊距 */font-weight: bold; /* 加粗 */color: white;/* 設置字體為楷體 */font-family: "楷體";}.navbar a {color: white; /* 鏈接顏色為白色 */text-decoration: none; /* 移除下劃線 */}/* 搜索表單樣式 */.search-form {display: flex;flex-wrap: nowrap;align-items: center;gap: 10px; /* 控件之間的間距 */margin: 20px 0;}.search-form input[type="text"], .search-form select {padding: 5px; /* 輸入框內邊距 */width: 260px; /* 寬度 */}.search-form button {padding: 5px 15px; /* 按鈕內邊距 */}/* 表格樣式 */table {width: 100%;border-collapse: collapse;}th, td {border: 1px solid #ddd; /* 邊框 */padding: 8px; /* 單元格內邊距 */text-align: center; /* 左對齊 */}th {background-color: #f2f2f2;font-weight: bold;}.avatar {width: 30px;height: 30px;}/* 頁腳樣式 */.footer {background-color: #b5b3b3; /* 灰色背景 */color: white; /* 白色文字 */text-align: center; /* 居中文本 */padding: 10px 0; /* 上下內邊距 */margin-top: 30px;}#container {width: 80%; /* 寬度為80% */margin: 0 auto; /* 水平居中 */}</style>
</head>
<body><div id="container"><!-- 頂部導航欄 --><div class="navbar"><h1>Tlias智能學習輔助系統</h1><a href="#">退出登錄</a></div><!-- 搜索表單區域 --><form class="search-form" action="/search" method="post"><label for="name">姓名:</label><input type="text" id="name" name="name" v-model="searchForm.name" placeholder="請輸入姓名"><label for="gender">性別:</label><select id="gender" name="gender" v-model="searchForm.gender"><option value=""></option><option value="1">男</option><option value="2">女</option></select><label for="position">職位:</label><select id="position" name="position" v-model="searchForm.job"><option value=""></option><option value="1">班主任</option><option value="2">講師</option><option value="3">學工主管</option><option value="4">教研主管</option><option value="5">咨詢師</option></select><button type="button" v-on:click="search">查詢</button><button type="button" @click="clear">清空</button></form><!-- 表格展示區 --><table><!-- 表頭 --><thead><tr><th>序號</th><th>姓名</th><th>性別</th><th>頭像</th><th>職位</th><th>入職日期</th><th>最后操作時間</th><th>操作</th></tr></thead><!-- 表格主體內容 --><tbody><tr v-for="(item, index) in empList" :key="item.id"><td>{{index+1}}</td><td>{{item.name}}</td><td>{{item.gender == 1 ?'男':'女'}}</td><!-- 插值表達式不能出現在標簽內部,只能出現在標簽屬性中 --><td><img class="avatar" v-bind:src="item.image" :alt="item.name"></td><td><span v-if="item.job==1">班主任</span><span v-else-if="item.job==2">講師</span><span v-else-if="item.job==3">學工主管</span><span v-else-if="item.job==4">教研主管</span><span v-else-if="item.job==5">咨詢師</span><span v-else>其他</span></td><!-- <td><span v-show="item.job==1">班主任</span><span v-show="item.job==2">講師</span><span v-show="item.job==3">學工主管</span><span v-show="item.job==4">教研主管</span><span v-show="item.job==5">咨詢師</span></td> --><td>{{item.entrydate}}</td><td>{{item.updatetime}}</td><td class="action-buttons"><button type="button">編輯</button><button type="button">刪除</button></td></tr></tbody></table><!-- 頁腳版權區域 --><footer class="footer"><p>江蘇傳智播客教育科技股份有限公司</p><p>版權所有 Copyright 2006-2024 All Rights Reserved</p></footer></div><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:'',job:''},empList:[]}},//定義方法methods: {async search(){//發送ajax請求獲取數據// axios.get(`https://web-server.itheima.net/emps/list?name=${this.searchForm.name}&gender=${this.searchForm.gender}&job=${this.searchForm.job}`).then((result) => {// this.empList = result.data.data;// })// console.log('===========================');let result = await axios.get(`https://web-server.itheima.net/emps/list?name=${this.searchForm.name}&gender=${this.searchForm.gender}&job=${this.searchForm.job}`);this.empList = result.data.data;},clear(){this.searchForm={name:'',gender:'',job:''};this.search(); }},//鉤子函數mounted() {//頁面加載完成后,發送ajax請求獲取數據this.search();},}).mount('#container')</script></body>
</html>