一、什么是AJAX ?
AJAX 是?異步的 JavaScript 和 XML(Asynchronous JavaScript And XML)?的縮寫,是一種實現瀏覽器與服務器進行數據通信的技術。其核心是通過?XMLHttpRequest
?對象在不重新刷新頁面的前提下,與服務器交換數據并更新頁面局部內容。
1.核心特性:
- 異步通信:無需刷新整個頁面,即可發送請求、接收響應,實現頁面動態更新(如加載省份列表、表單驗證等)。
- 支持多種數據格式:可發送和接收 JSON、XML、HTML、文本等格式的數據,其中 JSON 是最常用的格式。
- 瀏覽器與服務器交互:作為中間層,實現前端與后端的數據交互,提升用戶體驗(如無刷新提交表單、動態加載數據)。
2.通俗理解:
相當于在瀏覽器和服務器之間建立一條 “秘密通道”,允許瀏覽器在不重新加載整個頁面的情況下,單獨向服務器請求數據(如省份列表、用戶信息等),并將返回的數據局部更新到頁面上,使頁面 “動態化”。
3.學習路徑:
- 先使用?
axios
?庫:基于?XMLHttpRequest
?封裝的簡潔工具,簡化 AJAX 操作(如發送請求、處理響應),廣泛應用于 Vue、React 等框架中。 - 再了解底層原理:通過學習原生?
XMLHttpRequest
?對象,理解 AJAX 的底層實現機制(如請求狀態監聽、錯誤處理等)。
4.核心作用:
實現瀏覽器與服務器之間的?動態數據交互,避免頁面全量刷新,提升用戶體驗和開發效率。
5.怎么用AJAX ?
6.axios 使用
語法:
1.引入axios.js:https://unpkg.com/axios/dist/axios.min.js
這條鏈接打開的東西
2. 使用axios 函數
需求:請求目標資源地址,拿到省份列表數據,顯示到頁面
目標資源地址:http://hmajax.itheima.net/api/province
<!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><!--axios庫地址:https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js省份數據地址:http://hmajax.itheima.net/api/province目標: 使用axios庫, 獲取省份列表數據, 展示到頁面上1. 引入axios庫--><p class="my-p"></p><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>// 2. 使用axios函數axios({url: 'http://hmajax.itheima.net/api/province'}).then(result => {console.log(result)// 好習慣:多打印,確認屬性名console.log(result.data.list)console.log(result.data.list.join('<br>'))// 把準備好省份列表,插入到頁面document.querySelector('.my-p').innerHTML = result.data.list.join('<br>')})</script>
</body></html>
二、認識URL
1.定義:
2.URL 的組成
⑴.協議
http 協議:超文本傳輸協議,規定瀏覽器和服務器之間傳輸數據的格式
⑵.域名
域名:標記服務器在互聯網中方位
⑶資源路徑
資源路徑:標記資源在服務器下的具體位置
3.獲取- 新聞列表
需求:使用axios 從服務器拿到新聞列表數據
目標資源地址:http://hmajax.itheima.net/api/news
代碼如下:
<!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>認識URL</title>
</head><body><!-- 新聞數據地址: http://hmajax.itheima.net/api/news--><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>axios({url: 'http://hmajax.itheima.net/api/news'}).then(result => {console.log(result)})</script>
</body></html>
三、URL 查詢參數
定義:瀏覽器提供給服務器的額外信息,讓服務器返回瀏覽器想要的數據
語法:http://xxxx.com/xxx/xxx?參數名1=值1&參數名2=值2
<!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>查詢參數</title>
</head><body><!-- 城市列表: http://hmajax.itheima.net/api/city參數名: pname值: 省份名字--><p></p><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>axios({url: 'http://hmajax.itheima.net/api/city',// 查詢參數params: {pname: '遼寧省'}}).then(result => {console.log(result.data.list)document.querySelector('p').innerHTML = result.data.list.join('<br>')})</script>
</body></html>
1.案例:地區查詢
<!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>案例_地區查詢</title><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"><style>:root {font-size: 15px;}body {padding-top: 15px;}</style>
</head><body><div class="container"><form id="editForm" class="row"><!-- 輸入省份名字 --><div class="mb-3 col"><label class="form-label">省份名字</label><input type="text" value="北京" name="province" class="form-control province" placeholder="請輸入省份名稱" /></div><!-- 輸入城市名字 --><div class="mb-3 col"><label class="form-label">城市名字</label><input type="text" value="北京市" name="city" class="form-control city" placeholder="請輸入城市名稱" /></div></form><button type="button" class="btn btn-primary sel-btn">查詢</button><br><br><p>地區列表: </p><ul class="list-group"><!-- 示例地區 --><li class="list-group-item">東城區</li></ul></div><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>/*獲取地區列表: http://hmajax.itheima.net/api/area查詢參數:pname: 省份或直轄市名字cname: 城市名字*/// 目標: 根據省份和城市名字, 查詢地區列表// 1. 查詢按鈕-點擊事件document.querySelector('.sel-btn').addEventListener('click', () => {// 2. 獲取省份和城市名字let pname = document.querySelector('.province').valuelet cname = document.querySelector('.city').value// 3. 基于axios請求地區列表數據axios({url: 'http://hmajax.itheima.net/api/area',params: {pname,cname}}).then(result => {// console.log(result)// 4. 把數據轉li標簽插入到頁面上let list = result.data.listconsole.log(list)let theLi = list.map(areaName => `<li class="list-group-item">${areaName}</li>`).join('')console.log(theLi)document.querySelector('.list-group').innerHTML = theLi})})</script>
</body></html>
四、常用請求方法和數據提交
1.常用請求方法
⑴.數據提交-注冊賬號
場景:當數據需要在服務器上保存
- 需求:通過axios 提交用戶名和密碼,完成注冊功能
- 注冊用戶URL 地址:http://hmajax.itheima.net/api/register
- 請求方法:POST
- 參數名:
? ? ? ? ? username 用戶名(中英文和數字組成,最少8 位)
? ? ? ? ? ?password 密碼(最少6 位)
<!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>常用請求方法和數據提交</title>
</head><body><button class="btn">注冊用戶</button><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>/*注冊用戶:http://hmajax.itheima.net/api/register請求方法:POST參數名:username:用戶名(中英文和數字組成,最少8位)password:密碼 (最少6位)目標:點擊按鈕,通過axios提交用戶和密碼,完成注冊*/document.querySelector('.btn').addEventListener('click', () => {axios({url: 'http://hmajax.itheima.net/api/register',method: 'POST',data: {username: 'itheima789444444',password: '123456'}}).then(result => {console.log(result)})})</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>axios錯誤處理</title>
</head><body><button class="btn">注冊用戶</button><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>/*注冊用戶: http://hmajax.itheima.net/api/register請求方法: POST參數名:username: 用戶名 (中英文和數字組成, 最少8位)password: 密碼 (最少6位)目標: 點擊按鈕, 通過axios提交用戶和密碼, 完成注冊需求: 使用axios錯誤處理語法, 拿到報錯信息, 彈框反饋給用戶*/document.querySelector('.btn').addEventListener('click', () => {axios({url: 'http://hmajax.itheima.net/api/register',method: 'post',data: {username: 'itheima007',password: '7654321'}}).then(result => {// 成功console.log(result)}).catch(error => {// 失敗// 處理錯誤信息console.log(error)console.log(error.response.data.message)alert(error.response.data.message)})})</script>
</body></html>
五、HTTP協議-報文
HTTP 協議:規定了瀏覽器發送及服務器返回內容的格式
請求報文:瀏覽器按照HTTP 協議要求的格式,發送給服務器的內容
1.請求報文的格式
請求報文的組成部分有:
- 請求行:請求方法,URL,協議
- 請求頭:以鍵值對的格式攜帶的附加信息,比如:Content-Type(內容類型)
- 空行:分隔請求頭,空行之后的是發送給服務器的資源
- 請求體:發送的資源?
用以下代碼體驗如何在游覽器中查看請求報文
<!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>HTTP協議_請求報文</title>
</head><body><button class="btn">注冊用戶</button><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>/*注冊用戶:http://hmajax.itheima.net/api/register請求方法:POST參數名:username:用戶名(中英文和數字組成, 最少8位)password:密碼(最少6位)目標:運行后,查看請求報文*/document.querySelector('.btn').addEventListener('click', () => {axios({url: 'http://hmajax.itheima.net/api/register',method: 'post',data: {username: 'itheima00155667',password: '7654321'}}).then(result => {// 成功console.log(result)}).catch(error => {// 失敗// 處理錯誤信息console.log(error)console.log(error.response.data.message)alert(error.response.data.message)})})</script>
</body></html>
2.請求報文-錯誤排查
<!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>請求報文_輔助調試</title><!-- 引入bootstrap.css --><link rel="stylesheet"href="https://mirrors.tencent.com/stackpath.bootstrapcdn.com/bootstrap/5.2.2/css/bootstrap.min.css"><!-- 公共 --><style>html,body {background-color: #EDF0F5;width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;}.container {width: 520px;height: 540px;background-color: #fff;padding: 60px;box-sizing: border-box;}.container h3 {font-weight: 900;}</style><!-- 表單容器和內容 --><style>.form_wrap {color: #8B929D !important;}.form-text {color: #8B929D !important;}</style><!-- 提示框樣式 --><style>.alert {transition: .5s;opacity: 0;}.alert.show {opacity: 1;}</style>
</head><body><div class="container"><h3>歡迎-登錄</h3><!-- 登錄結果-提示框 --><div class="alert alert-success" role="alert">JS中會動態插入提示文字</div><!-- 表單 --><div class="form_wrap"><form><div class="mb-3"><label for="username" class="form-label">賬號名</label><input type="text" class="form-control username" name="username" aria-describedby="usernameHelp"></div><div class="mb-3"><label for="password" class="form-label">密碼</label><input type="password" class="form-control password" name="password"></div><button type="button" class="btn btn-primary btn-login"> 登 錄 </button></form></div></div><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>// 1.獲取 alertconst alertCom = document.querySelector('.alert')// 2.抽取提示框的方法function showAlert(msg, classname) {alertCom.innerText = msgalertCom.classList.add(classname)alertCom.classList.add('show')setTimeout(() => {// 延遲隱藏alertCom.classList.remove('show')alertCom.classList.remove(classname)}, 2000);}// 3.給登錄按鈕綁定點擊事件,提交輸入的用戶信息到服務器document.querySelector('.btn-login').addEventListener('click', function () {// 3.1 獲取輸入的用戶名和密碼const username = document.querySelector('.username').valueconst password = document.querySelector('.password').value// 3.2用戶名 密碼 長度判斷if (username.trim().length < 8) {showAlert('用戶名長度需要大于等于8', 'alert-danger')return}if (password.trim().length < 6) {showAlert('密碼長度需要大于等于6', 'alert-danger')return}// 3.3 通過axios提交到服務器 并 提示用戶 成功 / 失敗axios({url: 'http://hmajax.itheima.net/api/login',method: 'post',data: {username,password}}).then(res => {// 顯示提示框showAlert(res.data.message, 'alert-success')}).catch(err => {// 顯示警示框showAlert(err.response.data.message, 'alert-danger')})})</script>
</body></html>
這個看看就行
3.HTTP 協議-響應報文
HTTP 協議:規定了瀏覽器發送及服務器返回內容的格式
響應報文:服務器按照 HTTP 協議要求的格式,返回給瀏覽器的內容
- 響應行(狀態行):協議、HTTP 響應狀態碼、狀態信息
- 響應頭:以鍵值對的格式攜帶的附加信息,比如:Content-Type
- 空行:分隔響應頭,空行之后的是服務器返回的資源
- 響應體:返回的資源
4.HTTP 響應狀態碼
<!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>HTTP協議_響應報文</title>
</head><body><button class="btn">注冊用戶</button><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>/*注冊用戶: http://hmajax.itheima.net/api/register請求方法: POST參數名:username: 用戶名 (中英文和數字組成, 最少8位)password: 密碼 (最少6位)目標: 點擊按鈕, 通過axios提交用戶和密碼, 完成注冊需求: 使用axios錯誤處理語法, 拿到報錯信息, 彈框反饋給用戶*/document.querySelector('.btn').addEventListener('click', () => {axios({url: 'http://hmajax.itheima.net/api/registrweer1ddd',method: 'post',data: {username: 'itheima007',password: '7654321'}}).then(result => {// 成功console.log(result)}).catch(error => {// 失敗// 處理錯誤信息// console.log(error)console.log(error.response.data.message)// alert(error.response.data.message)})})</script>
</body></html>
六、接口文檔
接口文檔:描述接口的文章(后端工程師)
接口:使用 AJAX 和服務器通訊時,使用的 URL,請求方法,以及參數
傳送門:AJAX 階段接口文檔
七、案例-用戶登錄
<!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>案例_登錄</title><!-- 引入bootstrap.css --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"><!-- 公共 --><style>html,body {background-color: #EDF0F5;width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;}.container {width: 520px;height: 540px;background-color: #fff;padding: 60px;box-sizing: border-box;}.container h3 {font-weight: 900;}</style><!-- 表單容器和內容 --><style>.form_wrap {color: #8B929D !important;}.form-text {color: #8B929D !important;}</style><!-- 提示框樣式 --><style>.alert {transition: .5s;opacity: 0;}.alert.show {opacity: 1;}</style>
</head><body><div class="container"><h3>歡迎-登錄</h3><!-- 登錄結果-提示框 --><div class="alert alert-success" role="alert">提示消息</div><!-- 表單 --><div class="form_wrap"><form><div class="mb-3"><label for="username" class="form-label">賬號名</label><input type="text" class="form-control username"></div><div class="mb-3"><label for="password" class="form-label">密碼</label><input type="password" class="form-control password"></div><button type="button" class="btn btn-primary btn-login"> 登 錄 </button></form></div></div><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>// 目標1:點擊登錄時,用戶名和密碼長度判斷,并提交數據和服務器通信// 1.1 登錄-點擊事件document.querySelector('.btn-login').addEventListener('click', () => {// 1.2 獲取用戶名和密碼const username = document.querySelector('.username').valueconst password = document.querySelector('.password').value// console.log(username, password)// 1.3 判斷長度if (username.length < 8) {console.log('用戶名必須大于等于8位')return // 阻止代碼繼續執行}if (password.length < 6) {console.log('密碼必須大于等于6位')return // 阻止代碼繼續執行}// 1.4 基于axios提交用戶名和密碼// console.log('提交數據到服務器')axios({url: 'http://hmajax.itheima.net/api/login',method: 'POST',data: {username,password}}).then(result => {console.log(result)console.log(result.data.message)}).catch(error => {console.log(error)console.log(error.response.data.message)})})</script>
</body></html>
把提示消息升級一下
<!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>案例_登錄_提示消息</title><!-- 引入bootstrap.css --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"><!-- 公共 --><style>html,body {background-color: #EDF0F5;width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;}.container {width: 520px;height: 540px;background-color: #fff;padding: 60px;box-sizing: border-box;}.container h3 {font-weight: 900;}</style><!-- 表單容器和內容 --><style>.form_wrap {color: #8B929D !important;}.form-text {color: #8B929D !important;}</style><!-- 提示框樣式 --><style>.alert {transition: .5s;opacity: 0;}.alert.show {opacity: 1;}</style>
</head><body><div class="container"><h3>歡迎-登錄</h3><!-- 登錄結果-提示框 --><div class="alert alert-success" role="alert">提示消息</div><!-- 表單 --><div class="form_wrap"><form><div class="mb-3"><label for="username" class="form-label">賬號名</label><input type="text" class="form-control username"></div><div class="mb-3"><label for="password" class="form-label">密碼</label><input type="password" class="form-control password"></div><button type="button" class="btn btn-primary btn-login"> 登 錄 </button></form></div></div><script src="https://unpkg.com/axios/dist/axios.min.js"></script><script>// 目標1:點擊登錄時,用戶名和密碼長度判斷,并提交數據和服務器通信// 目標2:使用提示框,反饋提示消息// 2.1 獲取提示框const myAlert = document.querySelector('.alert')/*** 2.2 封裝提示框函數,重復調用,滿足提示需求* 功能:* 1. 顯示提示框* 2. 不同提示文字msg,和成功綠色失敗紅色isSuccess(true成功,false失敗)* 3. 過2秒后,讓提示框自動消失*/function alertFn(msg, isSuccess) {// 1> 顯示提示框myAlert.classList.add('show')// 2> 實現細節myAlert.innerText = msgconst bgStyle = isSuccess ? 'alert-success' : 'alert-danger'myAlert.classList.add(bgStyle)// 3> 過2秒隱藏setTimeout(() => {myAlert.classList.remove('show')// 提示:避免類名沖突,重置背景色myAlert.classList.remove(bgStyle)}, 2000)}// 1.1 登錄-點擊事件document.querySelector('.btn-login').addEventListener('click', () => {// 1.2 獲取用戶名和密碼const username = document.querySelector('.username').valueconst password = document.querySelector('.password').value// console.log(username, password)// 1.3 判斷長度if (username.length < 8) {alertFn('用戶名必須大于等于8位', false)console.log('用戶名必須大于等于8位')return // 阻止代碼繼續執行}if (password.length < 6) {alertFn('密碼必須大于等于6位', false)console.log('密碼必須大于等于6位')return // 阻止代碼繼續執行}// 1.4 基于axios提交用戶名和密碼// console.log('提交數據到服務器')axios({url: 'http://hmajax.itheima.net/api/login',method: 'POST',data: {username,password}}).then(result => {alertFn(result.data.message, true)console.log(result)console.log(result.data.message)}).catch(error => {alertFn(error.response.data.message, false)console.log(error)console.log(error.response.data.message)})})</script>
</body></html>
八、form-serialize 插件
語法:
<!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>form-serialize插件使用</title>
</head><body><form action="javascript:;" class="example-form"><input type="text" name="username"><br><input type="text" name="password"><br><input type="button" class="btn" value="提交"></form><!-- 目標:在點擊提交時,使用form-serialize插件,快速收集表單元素值1. 把插件引入到自己網頁中--><script src="./lib/form-serialize.js"></script><script>document.querySelector('.btn').addEventListener('click', () => {/*** 2. 使用serialize函數,快速收集表單元素的值* 參數1:要獲取哪個表單的數據* 表單元素設置name屬性,值會作為對象的屬性名* 建議name屬性的值,最好和接口文檔參數名一致* 參數2:配置對象* hash 設置獲取數據結構* - true:JS對象(推薦)一般請求體里提交給服務器* - false: 查詢字符串* empty 設置是否獲取空值* - true: 獲取空值(推薦)數據結構和標簽結構一致* - false:不獲取空值*/const form = document.querySelector('.example-form')const data = serialize(form, { hash: true, empty: true })// const data = serialize(form, { hash: false, empty: true })// const data = serialize(form, { hash: true, empty: false })console.log(data)})</script>
</body></html>
1.案例-用戶登錄
<!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>案例_登錄_插件使用</title><!-- 引入bootstrap.css --><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"><!-- 公共 --><style>html,body {background-color: #EDF0F5;width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;}.container {width: 520px;height: 540px;background-color: #fff;padding: 60px;box-sizing: border-box;}.container h3 {font-weight: 900;}</style><!-- 表單容器和內容 --><style>.form_wrap {color: #8B929D !important;}.form-text {color: #8B929D !important;}</style><!-- 提示框樣式 --><style>.alert {transition: .5s;opacity: 0;}.alert.show {opacity: 1;}</style>
</head><body><div class="container"><h3>歡迎-登錄</h3><!-- 登錄結果-提示框 --><div class="alert alert-success" role="alert">提示消息</div><!-- 表單 --><div class="form_wrap"><form class="login-form"><div class="mb-3"><label for="username" class="form-label">賬號名</label><input type="text" class="form-control username" name="username"></div><div class="mb-3"><label for="password" class="form-label">密碼</label><input type="password" class="form-control password" name="password"></div><button type="button" class="btn btn-primary btn-login"> 登 錄 </button></form></div></div><script src="https://unpkg.com/axios/dist/axios.min.js"></script><!-- 3.1 引入插件 --><script src="./lib/form-serialize.js"></script><script>// 目標1:點擊登錄時,用戶名和密碼長度判斷,并提交數據和服務器通信// 目標2:使用提示框,反饋提示消息// 目標3:使用form-serialize插件,收集用戶名和密碼// 2.1 獲取提示框const myAlert = document.querySelector('.alert')/**2.2 封裝提示框函數,重復調用,滿足提示需求* 功能:* 1. 顯示提示框* 2. 不同提示文字msg,和成功綠色失敗紅色isSuccess(true成功,false失敗)* 3. 過2秒后,讓提示框自動消失*/function alertFn(msg, isSuccess) {// 1> 顯示提示框myAlert.classList.add('show')// 2> 實現細節myAlert.innerText = msgconst bgStyle = isSuccess ? 'alert-success' : 'alert-danger'myAlert.classList.add(bgStyle)// 3> 過2秒隱藏setTimeout(() => {myAlert.classList.remove('show')// 提示:避免類名沖突,重置背景色myAlert.classList.remove(bgStyle)}, 2000)}// 1.1 登錄-點擊事件document.querySelector('.btn-login').addEventListener('click', () => {// 3.2 使用serialize函數,收集登錄表單里用戶名和密碼const form = document.querySelector('.login-form')const data = serialize(form, { hash: true, empty: true })console.log(data)// {username: 'itheima007', password: '7654321'}const { username, password } = data// 1.2 獲取用戶名和密碼// const username = document.querySelector('.username').value// const password = document.querySelector('.password').valueconsole.log(username, password)// 1.3 判斷長度if (username.length < 8) {alertFn('用戶名必須大于等于8位', false)console.log('用戶名必須大于等于8位')return // 阻止代碼繼續執行}if (password.length < 6) {alertFn('密碼必須大于等于6位', false)console.log('密碼必須大于等于6位')return // 阻止代碼繼續執行}// 1.4 基于axios提交用戶名和密碼// console.log('提交數據到服務器')axios({url: 'http://hmajax.itheima.net/api/login',method: 'POST',data: {username,password}}).then(result => {alertFn(result.data.message, true)console.log(result)console.log(result.data.message)}).catch(error => {alertFn(error.response.data.message, false)console.log(error)console.log(error.response.data.message)})})</script>
</body></html>