中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁 > news >正文

高端企業(yè)網(wǎng)站建設(shè)注意問題谷歌瀏覽器搜索入口

高端企業(yè)網(wǎng)站建設(shè)注意問題,谷歌瀏覽器搜索入口,建材網(wǎng)站建設(shè) 南寧,網(wǎng)站開發(fā)涉及內(nèi)容文章目錄 Day1 Ajax入門1.AJAX概念和axios的使用2. 認(rèn)識URL3.URL的查詢參數(shù)4.常用的請求方法和數(shù)據(jù)提交5.HTTP協(xié)議-報文6.接口文檔7.form-serialize插件8.案例用戶登錄 Day2 Ajax綜合案bootstrap彈框圖書管理圖片上傳更換背景個人信息設(shè)置 Day3 AJAX原理XMLHttpRequestPromise封…

文章目錄

    • Day1 Ajax入門
      • 1.AJAX概念和axios的使用
      • 2. 認(rèn)識URL
      • 3.URL的查詢參數(shù)
      • 4.常用的請求方法和數(shù)據(jù)提交
      • 5.HTTP協(xié)議-報文
      • 6.接口文檔
      • 7.form-serialize插件
      • 8.案例用戶登錄
    • Day2 Ajax綜合案
      • bootstrap彈框
      • 圖書管理
      • 圖片上傳
      • 更換背景
      • 個人信息設(shè)置
    • Day3 AJAX原理
      • XMLHttpRequest
      • Promise
      • 封裝簡易版axios
      • 案例-天氣預(yù)報
    • Day4 AJAX進階
      • 同步代碼和異步代碼
      • 回調(diào)函數(shù)地獄和Promise鏈?zhǔn)秸{(diào)用
      • async和await使用
      • 事件循環(huán)(EventLoop)
      • 宏任務(wù)與微任務(wù)-執(zhí)行任務(wù)
      • Promise.all靜態(tài)方法
      • 商品分類
      • 學(xué)習(xí)反饋
    • 總結(jié)

資料:
素材與資料都來自黑馬程序員
思維導(dǎo)圖
mdn網(wǎng)址

Day1 Ajax入門

1.AJAX概念和axios的使用

在這里插入圖片描述
概念:AJAX是瀏覽器與服務(wù)器進行數(shù)據(jù)通信的技術(shù)
作用:瀏覽器和服務(wù)器之間通信,動態(tài)數(shù)據(jù)交互。
怎么使用AJAX?

1.先使用axios庫,與服務(wù)器進行數(shù)據(jù)通信(使用場景:VUE,reat項目都會用到axios)
2.再學(xué)習(xí)XMLHttpREquest對象的使用,理解AJAX底層原理

axios使用:

  • 1.引入axios庫:
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  • 2.使用axios函數(shù)
    √ 傳入配置對象
    √ 再用.then回調(diào)函數(shù)接收結(jié)果,并做后續(xù)的處理
axios({url:'目標(biāo)資源地址'
}).then(result => {
//對服務(wù)器進行后續(xù)的處理
})

2. 認(rèn)識URL

URL:統(tǒng)一資源定位符,網(wǎng)址,用于訪問服務(wù)器資源
解釋url每個部分的作用:

http://hmajax.itheima.net /api/login
協(xié)議域名 資源路徑

在這里插入圖片描述

3.URL的查詢參數(shù)

定義:瀏覽器提供給服務(wù)器額外信息,讓服務(wù)器返回瀏覽器想要的數(shù)據(jù)
語法:http://xxxx.com/xxx/xxx?參數(shù)名1=值1&參數(shù)名2=值2
URL的查詢參數(shù)的作用:瀏覽器提供給服務(wù)器額外信息,獲取對應(yīng)的數(shù)據(jù)
axios-查詢參數(shù):
使用params選項,攜帶參數(shù)名和值
axios在運行時把參數(shù)名和值,會拼接到url?參數(shù)名=值

axios({url:'目標(biāo)資源地址',params:{參數(shù)名:值
}).then(result => {
//對服務(wù)器進行后續(xù)的處理
})

4.常用的請求方法和數(shù)據(jù)提交

請求方法:對服務(wù)器資源,要執(zhí)行的操作

請求方法操作
GET獲取數(shù)據(jù)
POST數(shù)據(jù)提交
PUT修改數(shù)據(jù)(全部)
DELETE刪除數(shù)據(jù)
PATCH修改數(shù)據(jù)(部分)

數(shù)據(jù)提交:當(dāng)數(shù)據(jù)需要在服務(wù)器上保存
axios請求配置:

  • url:請求的URL網(wǎng)址
  • method:請求的方法,GET可以省略(不區(qū)分大小寫)
  • data:提交數(shù)據(jù)
axios({url:'目標(biāo)資源地址',params:{參數(shù)名:值},data:{參數(shù)名:值}
}).then(result => {
//對服務(wù)器進行后續(xù)的處理
})

axios-錯誤處理

axios({//請求選項
}).then(result => {//處理數(shù)據(jù)
}).catch(error => {//處理錯誤
})

5.HTTP協(xié)議-報文

  • 請求報文:瀏覽器發(fā)送給服務(wù)器的內(nèi)容叫做請求報文
  • 請求報文的組成:

1.請求行:請求方法,URL,協(xié)議
2.請求頭:以鍵值對的格式攜帶的附加信息,比如Content-Type
3.空行:分隔請求頭,空行之后的是發(fā)送給服務(wù)器的資源(感覺我的瀏覽器有點不一樣)
4.請求體:發(fā)送的資源

  • 通過Chrome的網(wǎng)絡(luò)面板查看請求報文

在這里插入圖片描述
在這里插入圖片描述

在這里插入圖片描述

響應(yīng)報文的組成:

  • 1.響應(yīng)行:協(xié)議、Http響應(yīng)狀態(tài)碼、狀態(tài)信息
  • 2.響應(yīng)頭:鍵值對的格式攜帶的附加信息,比如Content-Type
  • 3.空行:分隔響應(yīng)頭,空行之后的是返回給瀏覽器的資源
  • 4.響應(yīng)體:返回的資源
    在這里插入圖片描述
    在這里插入圖片描述

Http響應(yīng)狀態(tài)碼:用來表明請求是否成功完成。

狀態(tài)碼說明
1xx信息
2xx成功
3xx重定向消息
4xx客戶端錯誤
5xx服務(wù)端錯誤

6.接口文檔

接口文檔:由后端提供的描述接口的文章
在這里插入圖片描述

7.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>13.form-serialize插件使用</title>
</head><body><form action="javascript:;" class="example-form"><input type="text" name="uname"><br><input type="text" name="pwd"><br><input type="button" class="btn" value="提交"></form><!-- 目標(biāo):在點擊提交時,使用form-serialize插件,快速收集表單元素值--><script>document.querySelector('.btn').addEventListener('click', () => {})</script>
</body></html>
 <script src="./lib/form-serialize.js"></script><script>document.querySelector('.btn').addEventListener('click', () => {/* 2.使用serialize函數(shù),快速收集表單元素的值參數(shù)1:要獲得哪個表單的數(shù)據(jù)表單元素設(shè)置name屬性,值會作為對象的屬性名建議name屬性的值,最好和接口文檔參數(shù)名一致參數(shù)2:配置對象hash:設(shè)置獲取數(shù)據(jù)結(jié)構(gòu)-true:JS對象(推薦) 一般請求體里提交給服務(wù)器-false;查詢字符串empty:設(shè)置是否獲取空值-true:獲取空值(推薦)數(shù)據(jù)結(jié)構(gòu)和標(biāo)簽結(jié)構(gòu)一致-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>

8.案例用戶登錄

素材:

<!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>12.案例_登錄_提示消息</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><!-- 表單容器和內(nèi)容 --><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><!-- 登錄結(jié)果-提示框 --><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://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>// 目標(biāo)1:點擊登錄時,用戶名和密碼長度判斷,并提交數(shù)據(jù)和服務(wù)器通信// 目標(biāo)2:使用提示框,反饋提示消息// 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 // 阻止代碼繼續(xù)執(zhí)行}if (password.length < 6) {console.log('密碼必須大于等于6位')return // 阻止代碼繼續(xù)執(zhí)行}// 1.4 基于axios提交用戶名和密碼// console.log('提交數(shù)據(jù)到服務(wù)器')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>
 <script>// 目標(biāo)1:點擊登錄時,用戶名和密碼長度判斷,并提交數(shù)據(jù)和服務(wù)器通信// 目標(biāo)2:使用提示框,反饋提示消息// 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 // 阻止代碼繼續(xù)執(zhí)行}if (password.length < 6) {console.log('密碼必須大于等于6位')return // 阻止代碼繼續(xù)執(zhí)行}// 1.4 基于axios提交用戶名和密碼// console.log('提交數(shù)據(jù)到服務(wù)器')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>

在這里插入圖片描述

Day2 Ajax綜合案

bootstrap彈框

bootstrap中文文檔

  • 屬性控制方式
<!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>Bootstrap 彈框</title><!-- 引入bootstrap.css --><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head><body><!-- 目標(biāo):使用Bootstrap彈框1. 引入bootstrap.css 和 bootstrap.js2. 準(zhǔn)備彈框標(biāo)簽,確認(rèn)結(jié)構(gòu)3. 通過自定義屬性,控制彈框的顯示和隱藏--><button type="button" class="btn btn-primary" data-bs-target = '.my-box' data-bs-toggle="modal">顯示彈框</button><!-- 彈框標(biāo)簽 bootstrap的標(biāo)簽modal彈框:添加modal類名(默認(rèn)隱藏)--><div class="modal my-box" tabindex="-1"><div class="modal-dialog"><!-- 彈框內(nèi)容 --><div class="modal-content"><div class="modal-header"><h5 class="modal-title">Modal title</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><p>Modal body text goes here.</p></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button><button type="button" class="btn btn-primary">Save changes</button></div></div></div></div><!-- 引入bootstrap.js --><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js"></script>
</body></html>
  • js屬性控制
<!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>Bootstrap 彈框</title><!-- 引入bootstrap.css --><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head><body><!-- 目標(biāo):使用JS控制彈框,顯示和隱藏1. 創(chuàng)建彈框?qū)ο?. 調(diào)用彈框?qū)ο髢?nèi)置方法.show() 顯示.hide() 隱藏--><button type="button" class="btn btn-primary edit-btn">編輯姓名</button><div class="modal name-box" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">請輸入姓名</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><form action=""><span>姓名:</span><input type="text" class="username"></form></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button><button type="button" class="btn btn-primary save-btn">保存</button></div></div></div></div><!-- 引入bootstrap.js --><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js"></script><script>// q.創(chuàng)建彈框?qū)ο?/span>const modalDom = document.querySelector('.name-box')const modal = new bootstrap.Modal(modalDom)// 編輯姓名-->點擊-->賦予默認(rèn)姓名 -->彈框顯示document.querySelector('.edit-btn').addEventListener('click',()=>{document.querySelector('.username').value = '默認(rèn)姓名'// 顯示彈框modal.show()})
//  保存-->點擊--->彈框隱藏document.querySelector('.save-btn').addEventListener('click',()=>{const username = document.querySelector('.username').value console.log('模擬將姓名保存在服務(wù)器當(dāng)中',username);// 隱藏彈框modal.hide()})</script></body></html>

圖書管理

步驟如下:

  • 目標(biāo)1:渲染圖書列表
    1.1 獲取數(shù)據(jù)
    1.2 渲染數(shù)據(jù)

const creator = '老張'
// 封裝-獲取被渲染圖書列表函數(shù)
function getBookList(){// 1.1獲取數(shù)據(jù)axios({url:'http://hmajax.itheima.net/api/books',params:{// 外號:獲取對應(yīng)數(shù)據(jù)creator}}).then(result => {// console.log(result);// console.log(result.data.data);const bookList = result.data.data// 1.2渲染數(shù)據(jù)const htmlStr = bookList.map((item,index) => {return `<tr><td>${index+1}</td><td>${item.bookname}</td><td>${item.author}</td><td>${item.publisher}</td><td data-id=${item.id}><span class="del">刪除</span><span class="edit">編輯</span></td></tr>  `    }).join('')// console.log(htmlStr);document.querySelector('.list').innerHTML = htmlStr})
}
getBookList()
  • 目標(biāo)2:新增圖書
    2.1新增彈框–>顯示和隱藏
    2.2 收集表單數(shù)據(jù),并提交到服務(wù)器保存
    2.3 刷新圖示列表
// 2.1創(chuàng)建彈框?qū)ο?/span>
const addModalDom = document.querySelector('.add-modal')
const addModal =new bootstrap.Modal(addModalDom)
// 保存按鈕->點擊->隱藏彈框
document.querySelector('.add-btn').addEventListener('click',() => {// 2.2 收集表單數(shù)據(jù),并提交到服務(wù)器const addForm = document.querySelector('.add-form')const bookObj = serialize(addForm,{hash:true,empty:true})console.log(bookObj);
//   提交到服務(wù)器
axios({url:'http://hmajax.itheima.net/api/books',method:'post',data:{...bookObj,creator}
}).then(result => {console.log(result);// 2.3添加成功之后,重新請求并渲染圖書列表getBookList()// 重置表單addForm.reset()// 隱藏彈框addModal.hide()})
})
  • 目標(biāo)3: 刪除圖書
    3.1 刪除元素綁定點擊事件 -> 獲取圖書id
    3.2 調(diào)用刪除接口
    3.3刷新圖書列表

// 3.1 刪除元素綁定點擊事件 -> 獲取圖書id
// 事件委托
document.querySelector('.list').addEventListener('click',e => {// 獲取觸發(fā)事件目標(biāo)元素// 判斷點擊的是刪除元素if(e.target.classList.contains('del')){// console.log('刪除元素');// 獲取圖書id(自定義屬性)const theId = e.target.parentNode.dataset.idconsole.log(theId);// 3.2 調(diào)用刪除接口axios({url:`http://hmajax.itheima.net/api/books/${theId}`,method:'delete'}).then(() => {// 3.3刷新圖書列表getBookList()})}
})
  • 目標(biāo)4:編輯圖書
    4.1 編輯彈框->顯示和隱藏
    4.2 獲取當(dāng)前編輯圖書數(shù)據(jù) -> 回顯到編輯表單中
    4.3 提交保存修改,并刷新列表
// 4.1 編輯彈框->顯示和隱藏
const editDom = document.querySelector('.edit-modal')
const editModal = new bootstrap.Modal(editDom)
// 編輯元素 -> 點擊彈框->彈框顯示
document.querySelector('.list').addEventListener('click',e => {// 判斷點擊的是否是編輯元素if(e.target.classList.contains('edit')){// 4.2 獲取當(dāng)前編輯圖書數(shù)據(jù) -> 回顯到編輯表單中const theId = e.target.parentNode.dataset.idaxios({url:`http://hmajax.itheima.net/api/books/${theId}`}).then((result) => {const bookObj = result.data.data// 數(shù)據(jù)對象“屬性”和標(biāo)簽“類名”一致// 遍歷數(shù)據(jù)對象,使用屬性去獲得對應(yīng)的標(biāo)簽,快速賦值const keys = Object.keys(bookObj)console.log(keys);// ['id', 'bookname', 'author', 'publisher']keys.forEach(key => {document.querySelector(`.edit-form .${key}`).value = bookObj[key]})})editModal.show()}
})
// 修改按鈕->點擊->隱藏彈框
document.querySelector('.edit-btn').addEventListener('click',()=>{
// 4.3 提交保存修改,并刷新列表const  editForm = document.querySelector('.edit-form')const{id,bookname,author,publisher} = serialize(editForm,{hash: true,empty:true})
//    保存正在編輯的圖書id,隱藏起來:無需用戶修改
// <input type="hidden" class="id" name="id" value="230530">axios({url:`http://hmajax.itheima.net/api/books/${id}`,method:'put',data:{bookname,author,publisher,creator}}).then(() => {// 修改成功以后,重新1獲取并刷新列表getBookList()})editModal.hide()
})

圖片上傳

   1. 獲取圖片文件2. 使用 FormData 攜帶圖片文件3. 提交到服務(wù)器,獲取圖片url網(wǎng)址使用
 <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>//  文件選擇元素->change事件document.querySelector('.upload').addEventListener('change',e => {// 1. 獲取圖片文件// console.dir(e.target)console.log(e.target.files[0]);// 2. 使用 FormData 攜帶圖片文件const fd = new FormData()fd.append('img',e.target.files[0])// 3. 提交到服務(wù)器,獲取圖片url網(wǎng)址使用axios({url:'http://hmajax.itheima.net/api/uploadimg',method:'post',data:fd}).then(result => {console.log(result);// 取出url位置,用img標(biāo)簽加載顯示const imgUrl = result.data.data.urldocument.querySelector('.my-img').src = imgUrl})})</script>

更換背景

   目標(biāo):網(wǎng)站-更換背景1. 選擇圖片上傳,設(shè)置body背景2. 上傳成功時,"保存"圖片url網(wǎng)址3. 網(wǎng)頁運行后,"獲取"url網(wǎng)址使用

document.querySelector('.bg-ipt').addEventListener('change',e => {// 1. 選擇圖片上傳,設(shè)置body背景// console.log(e.target.files[0]);const fd = new FormData()fd.append('img',e.target.files[0])//  提交到服務(wù)器,獲取圖片url網(wǎng)址使用axios({url:'http://hmajax.itheima.net/api/uploadimg',method:'post',data:fd}).then(result => {//    console.dir(result);  const imgUrl = result.data.data.urldocument.body.style.backgroundImage = `url(${imgUrl})`// 2. 上傳成功時,"保存"圖片url網(wǎng)址localStorage.setItem('bgImg',imgUrl)})
})// 網(wǎng)頁運行后,"獲取"url網(wǎng)址使用
const bgUrl = localStorage.getItem('bgImg')
console.log(bgUrl);
bgUrl &&  (document.body.style.backgroundImage = `url(${bgUrl})`)

個人信息設(shè)置

  目標(biāo)1:信息渲染1.1 獲取用戶的數(shù)據(jù)1.2 回顯數(shù)據(jù)到標(biāo)簽上

const creator = '張三'
axios({url:`http://hmajax.itheima.net/api/settings`,params:{creator}
}).then(result => {const userObj = result.data.dataconsole.log(userObj);// 1.2回顯數(shù)據(jù)到標(biāo)簽上Object.keys(userObj).forEach(key => {if(key === 'avatar'){// 賦予默認(rèn)頭像document.querySelector('.prew').src = userObj[key]}else if(key === 'gender'){// 賦予默認(rèn)性別// 獲取性別單選框:[男radio元素,女radio元素]const gRadioList = document.querySelectorAll('.gender')// 獲取性別數(shù)字:0男,1女const gNum = userObj[key]// 通過性別數(shù)字,作為下標(biāo),找到對應(yīng)性別單選框,設(shè)置選中狀態(tài)gRadioList[gNum].checked = true}else{// 賦予默認(rèn)值document.querySelector(`.${key}`).value = userObj[key]}})
})
目標(biāo)2:修改頭像2.1 獲取頭像文件2.2 提交服務(wù)器并更新頭像

// 文件選擇元素->change事件
document.querySelector('.upload').addEventListener('change',e => {// 2.1獲取頭像console.log(e.target.files[0]);const fd = new FormData()fd.append('avatar',e.target.files[0])fd.append('creator',creator)// 2.2 提交服務(wù)器并更新頭像axios({url:"http://hmajax.itheima.net/api/avatar",method:'put',data:fd}).then(result => {console.log(result);// data.data.avatarconst imgUrl = result.data.data.avatardocument.querySelector('.prew').src = imgUrl})})

/*

目標(biāo)3:提交表單3.1 收集表單元素3.2 提交到服務(wù)器
目標(biāo)4:結(jié)果顯示4.1 創(chuàng)建toast對象4.2 調(diào)用show方法-> 顯示提示框

// 保存修改-點擊
document.querySelector('.submit').addEventListener('click',() => {// 3.1 收集表單元素const userForm = document.querySelector('.user-form')const userObj = serialize(userForm,{hash:true,empty:true})userObj.creator = creator// 性別數(shù)字字符串,轉(zhuǎn)成數(shù)字類型userObj.gender = +userObj.genderconsole.log(userObj);// 3.2提交給服務(wù)器axios({url:"http://hmajax.itheima.net/api/settings",method:'put',data:userObj}).then( result => {// 4.1 創(chuàng)建toast對象const toastDom = document.querySelector('.my-toast')const toast = new bootstrap.Toast(toastDom)// 4.2 調(diào)用show方法-> 顯示提示框toast.show()})
})

Day3 AJAX原理

XMLHttpRequest

XMLHttpRequest(XHR)對象用于與服務(wù)器交互。通過 XMLHttpRequest 可以在不刷新頁面的情況下請求特定 URL,獲取數(shù)據(jù)。這允許網(wǎng)頁在不影響用戶操作的情況下,更新頁面的局部內(nèi)容。XMLHttpRequest 在 AJAX 編程中被大量使用。
AJAX原理:XMLHttpRequest對象;
學(xué)習(xí)XHR原因:

1.有更多與服務(wù)器數(shù)據(jù)通信方式
2.了解axios內(nèi)部原理

XHR使用步驟:

  • 創(chuàng)建XHR對象
  • 調(diào)用open方法,設(shè)置url和請求方法
  • 監(jiān)聽loadend事件,接收結(jié)果
  • 調(diào)用send方法,發(fā)起請求
let xhr = new XMLHttpRequest()
xhr.open('請求方法','請求url網(wǎng)址')
xhr.addEventlistener('loadend',()=>{//響應(yīng)結(jié)果console.log(xhr.response)  接收響應(yīng)
})
xhr.send() 發(fā)送請求

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

Promise

概念:表示(管理)一個異步操作最終狀態(tài)結(jié)果值的對象

好處:

1.邏輯清晰
2.了解axios函數(shù)內(nèi)部運作機制
3.能解決回調(diào)函數(shù)地獄問題

學(xué)習(xí)promise對象原因:
√ 成功和失敗狀態(tài),可以管理對于處理程序
√ 了解axios內(nèi)部原理
promise使用步驟:

  <script>/*** 目標(biāo):使用Promise管理異步任務(wù)*///  1.創(chuàng)建promise對象(pending待定狀態(tài))const p = new Promise((resolve, reject) => {// Promise對象創(chuàng)建,這里的代碼都會執(zhí)行// 2.執(zhí)行代碼setTimeout(() => {// resolve()=>'fulfilled狀態(tài)--已兌現(xiàn)'=> then()   resolve('模擬AJAX請求-成功結(jié)果')// reject()=>'reject狀態(tài)--已拒絕'=> catch()reject(new Error('模擬AJAX請求-失敗結(jié)果'))}, 2000)})console.log(p);// 3.獲取結(jié)果p.then(result => {console.log(result);}).catch(error => {console.log(error);})</script>

在這里插入圖片描述

 目標(biāo):使用Promise管理XHR請求省份列表1. 創(chuàng)建Promise對象2. 執(zhí)行XHR異步代碼,獲取省份列表3. 關(guān)聯(lián)成功或失敗函數(shù),做后續(xù)處理
 <script>//   1. 創(chuàng)建Promise對象const p = new Promise((resolve,reject)=> {// 2. 執(zhí)行XHR異步代碼,獲取省份列表const xhr = new XMLHttpRequest()xhr.open('GET','http://hmajax.itheima.net/api/province')xhr.addEventListener('loadend',()=>{//  xhr如何判斷響應(yīng)成功還是失敗的?// 2xx開頭的都是成功響應(yīng)狀態(tài)碼console.log(xhr);if(xhr.status >= 200 && xhr.status < 300){resolve(JSON.parse(xhr.response))}else{reject(new Error(xhr.response))}})xhr.send()})//3. 關(guān)聯(lián)成功或失敗函數(shù),做后續(xù)處理p.then((result)=>{console.log(result);document.querySelector('.my-p').innerHTML = result.list.join('<br>')}).catch(error=>{// 錯誤對象要用console.dir詳細(xì)打印console.dir(error);//  服務(wù)器返回錯誤提示消息,插入p標(biāo)簽document.querySelector('.my-p').innerHTML = error.message}) </script>

封裝簡易版axios

  目標(biāo):封裝_簡易axios函數(shù)_獲取省份列表1. 定義myAxios函數(shù),接收配置對象,返回Promise對象2. 發(fā)起XHR請求,默認(rèn)請求方法為GET3. 調(diào)用成功/失敗的處理程序4. 使用myAxios函數(shù),獲取省份列表展示
<script>// 1. 定義myAxios函數(shù),接收配置對象,返回Promise對象function myAxios(config){return new Promise((resolve,reject) =>{// 2. 發(fā)起XHR請求,默認(rèn)請求方法為GETconst xhr = new XMLHttpRequest()xhr.open('GET'||config.method,config.url)//  3. 調(diào)用成功/失敗的處理程序xhr.addEventListener('loadend',()=>{if(xhr.status >= 200 && xhr.status < 300){resolve(JSON.parse(xhr.response))}else{reject(new Error(xhr.response))}})xhr.send()})}myAxios({url:'http://hmajax.itheima.net/api/province'}).then(result => {console.log(result);document.querySelector('.my-p').innerHTML = result.list.join('<br>')}).catch(error => {console.dir(error);document.querySelector('.my-p').innerHTML = error.message})</script>
  目標(biāo):封裝_簡易axios函數(shù)_獲取地區(qū)列表1. 判斷有params選項,攜帶查詢參數(shù)2. 使用URLSearchParams轉(zhuǎn)換,并攜帶到url上3. 使用myAxios函數(shù),獲取地區(qū)列表
<script>function myAxios(config) {if(config.params){const paramsObj = new URLSearchParams(config.params)const queryString = paramsObj.toString()config.url = config.url+`?${queryString}`}return new Promise((resolve, reject) => {const xhr = new XMLHttpRequest()xhr.open(config.method || 'GET', config.url)xhr.addEventListener('loadend', () => {if (xhr.status >= 200 && xhr.status < 300) {resolve(JSON.parse(xhr.response))} else {reject(new Error(xhr.response))}})xhr.send()})}myAxios({url:'http://hmajax.itheima.net/api/area',params:{pname:'廣東省',cname:'河源市'}}).then((result)=>{console.log(result);document.querySelector('.my-p').innerHTML = result.list.join('<br>')}).catch(error=>{// 錯誤對象要用console.dir詳細(xì)打印console.dir(error);//  服務(wù)器返回錯誤提示消息,插入p標(biāo)簽document.querySelector('.my-p').innerHTML = error.message}) </script>
 目標(biāo):封裝_簡易axios函數(shù)_注冊用戶1. 判斷有data選項,攜帶請求體2. 轉(zhuǎn)換數(shù)據(jù)類型,在send中發(fā)送3. 使用myAxios函數(shù),完成注冊用戶
<script>function myAxios(config) {return new Promise((resolve, reject) => {const xhr = new XMLHttpRequest()if (config.params) {const paramsObj = new URLSearchParams(config.params)const queryString = paramsObj.toString()config.url += `?${queryString}`}xhr.open(config.method || 'GET', config.url)xhr.addEventListener('loadend', () => {if (xhr.status >= 200 && xhr.status < 300) {resolve(JSON.parse(xhr.response))} else {reject(new Error(xhr.response))}})if(config.data){// 告訴服務(wù)器,我傳遞的內(nèi)容類型是JSON字符串xhr.setRequestHeader('Content-Type','application/json')// 準(zhǔn)備數(shù)據(jù)并轉(zhuǎn)成JSON字符串xhr.send(JSON.stringify(config.data))}else{xhr.send()}   })}document.querySelector('.reg-btn').addEventListener('click',() =>{myAxios({url:'http://hmajax.itheima.net/api/register',method:'POST',data:{username:'zz111111111222',password:'12345111226'}}).then((result)=>{console.log(result);//  document.querySelector('.my-p').innerHTML = result.list.join('<br>')}).catch(error=>{// 錯誤對象要用console.dir詳細(xì)打印console.dir(error);//  服務(wù)器返回錯誤提示消息,插入p標(biāo)簽//  document.querySelector('.my-p').innerHTML = error.message}) })</script>

案例-天氣預(yù)報

   目標(biāo)1:默認(rèn)顯示-北京市天氣1.1 獲取北京市天氣數(shù)據(jù)1.2 數(shù)據(jù)展示到頁面

// 獲取并渲染城市天氣函數(shù)


function getWeather(cityCode){
// 1.1獲取北京市天氣數(shù)據(jù)myAxios({url:'http://hmajax.itheima.net/api/weather',params:{city:cityCode }}).then(result => {console.log(result);const wObj = result.data// 1.2數(shù)據(jù)展示到頁面const dateStr = `   <span class="dateShort">${wObj.date}</span><span class="calendar">農(nóng)歷&nbsp;<span class="dateLunar">${wObj.dateLunar}</span>`document.querySelector('.title').innerHTML=dateStr//   城市名字document.querySelector('.area').innerHTML = wObj.area// 當(dāng)天天氣const nowWStr = ` <div class="tem-box"><span class="temp"><span class="temperature">${wObj.temperature}</span><span>°</span></span></div><div class="climate-box"><div class="air"><span class="psPm25">${wObj.psPm25}</span><span class="psPm25Level">${wObj.psPm25Level}</span></div><ul class="weather-list"><li><img src=${wObj.weatherImg} class="weatherImg" alt=""><span class="weather">${wObj.weather}</span></li><li class="windDirection">${wObj.windDirection}</li><li class="windPower">${wObj.windPower}</li></ul></div>`document.querySelector('.weather-box').innerHTML = nowWStr
//   當(dāng)前天氣const twObj = wObj.todayWeatherconsole.log(twObj);const todayWStr = `<div class="range-box"><span>今天:</span><span class="range"><span class="weather">${twObj.weather}</span><span class="temNight">${twObj.temNight}</span><span>-</span><span class="temDay">${twObj.temDay}</span><span>℃</span></span>
</div>
<ul class="sun-list"><li><span>紫外線</span><span class="ultraviolet">${twObj.ultraviolet}</span></li><li><span>濕度</span><span class="humidity">${twObj.humidity}</span>%</li><li><span>日出</span><span class="sunriseTime">${twObj.sunriseTime}</span></li><li><span>日落</span><span class="sunsetTime">${twObj.sunsetTime}</span></li>
</ul>`
document.querySelector('.today-weather').innerHTML =  todayWStr
// 7天天氣預(yù)報
const dayForecast = wObj.dayForecast
const dayForecastStr = dayForecast.map(item =>{return `<li class="item"><div class="date-box"><span class="dateFormat">${item.dateFormat}</span><span class="date">${item.date}</span></div><img src="${item.weatherImg}" alt="" class="weatherImg"><span class="weather">${item.weather}</span><div class="temp"><span class="temNight">${item.temNight}</span>-<span class="temDay">${item.temDay}</span><span>℃</span></div><div class="wind"><span class="windDirection">${item.windDirection}</span><span class="windPower">&lt;${item.windPower}</span></div></li>`
}).join('')
document.querySelector('.week-wrap').innerHTML=dayForecastStr}).catch(error =>{console.log(error);})
}
//默認(rèn)進入網(wǎng)頁-就要獲取天氣數(shù)據(jù)
getWeather('110100')
目標(biāo)2:搜索城市列表2.1綁定input手機開你,獲取關(guān)鍵字2.2獲取城市列表數(shù)據(jù)

// 2.1綁定input手機開你,獲取關(guān)鍵字
document.querySelector('.search-city').addEventListener('input',e => {// 2.2獲取城市列表數(shù)據(jù)console.log(e.target.value);myAxios({url:'http://hmajax.itheima.net/api/weather/city',params:{city: e.target.value}}).then(result => {console.log(result);const liStr = result.data.map(item => {return `<li class="city-item" data-code=${item.code}>${item.name}</li>`}).join('')console.log(liStr);const a =document.querySelector('.search-list').innerHTML = liStrconsole.log(a);}).catch(error => {console.dir(error)})
})
目標(biāo)3:切換城市天氣3.1綁定城市點擊事件,獲取城市code值3.2 調(diào)用獲取并展示天氣的函數(shù)
document.querySelector('.search-list').addEventListener('click',e => {if(e.target.tagName === 'LI'){getWeather(e.target.dataset.code)}
})

Day4 AJAX進階

同步代碼和異步代碼

同步代碼:逐行執(zhí)行,需原地等待結(jié)果后,才繼續(xù)向下執(zhí)行
異步代碼:調(diào)用后耗時,不阻塞代碼繼續(xù)執(zhí)行(不必原地等待),在將來完成后觸發(fā)一個回調(diào)函數(shù)。
Js中的異步代碼:setTimeout/setInterval,事件,AJAX

回調(diào)函數(shù)地獄和Promise鏈?zhǔn)秸{(diào)用

1.回調(diào)函數(shù)地獄
在回調(diào)函數(shù)一直向下嵌套回調(diào)函數(shù),形成回調(diào)函數(shù)地獄
目標(biāo):演示回調(diào)函數(shù)地獄
需求:獲取默認(rèn)第一個省,第一個市,第一個地區(qū)并展示在下拉菜單中
概念:在回調(diào)函數(shù)中嵌套回調(diào)函數(shù),一直嵌套下去就形成了回調(diào)函數(shù)地獄
缺點:可讀性差,異常無法獲取,耦合性嚴(yán)重,牽一發(fā)動全身

 <script>axios({url:'http://hmajax.itheima.net/api/province'}).then(result => {const pname = result.data.list[0]document.querySelector('.province').innerHTML = pname// 2.獲取默認(rèn)第一個城市的名字axios({url:'http://hmajax.itheima.net/api/city', params:{pname}}).then(result => {const cname = result.data.list[0]document.querySelector('.city').innerHTML = cname// 3.獲取默認(rèn)第一個地區(qū)的名字axios({url:'http://hmajax.itheima.net/api/area',params:{pname,cname}}).then(result => {const areaName = result.data.list[0]document.querySelector('.area').innerHTML = areaName})})})</script>

2.Promise的鏈?zhǔn)秸{(diào)用–入門
概念:依靠then()方法會返回一個新生成的Promise對象特性,繼續(xù)初戀下一環(huán)任務(wù),直到結(jié)束
細(xì)節(jié):then()回調(diào)函數(shù)中的返回值,會影響新生成的Promise對象最終狀態(tài)和結(jié)果
目標(biāo):掌握Promise的鏈?zhǔn)秸{(diào)用
需求:把省市的嵌套結(jié)構(gòu),改成鏈?zhǔn)秸{(diào)用的線性結(jié)構(gòu)

  <script>//  1.創(chuàng)建Promise對象-模擬請求省份名字const p = new Promise((resolve, reject) => {setTimeout(() => {resolve('北京市')}, 2000)})// 2.獲取省份的名字const p2 = p.then(result => {return new Promise((resolve, reject) => {setTimeout(() => {resolve(result + '-----北京市')}, 2000)})})// 4.獲取城市名字p2.then(result => {console.log(result);})</script>

在這里插入圖片描述
3.解決回調(diào)函數(shù)地獄

目標(biāo):把回調(diào)函數(shù)嵌套代碼,改成Promise鏈?zhǔn)秸{(diào)用結(jié)構(gòu)
需求:獲取默認(rèn)第一個省,第一個市,第一個地區(qū)并展示在下拉菜單中
 <script>let pname = ''axios({url:'http://hmajax.itheima.net/api/province'}).then(result => {pname = result.data.list[0]document.querySelector('.province').innerHTML = pname// 2.獲取默認(rèn)第一個城市的名字return axios({url:'http://hmajax.itheima.net/api/city', params:{pname}}).then(result => {const cname = result.data.list[0]document.querySelector('.city').innerHTML = cname// 3.獲取默認(rèn)第一個地區(qū)的名字return axios({url:'http://hmajax.itheima.net/api/area',params:{pname,cname}}).then(result => {const areaName = result.data.list[0]document.querySelector('.area').innerHTML = areaName})})})

async和await使用

概念;在async函數(shù)內(nèi),使用await關(guān)鍵字取代then函數(shù),等待獲取Promise對象成功狀態(tài)的結(jié)果值
async函數(shù)和await捕獲錯誤:使用 try…catch…

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>/*** 目標(biāo):掌握async和await語法,解決回調(diào)函數(shù)地獄* 概念:在async函數(shù)內(nèi),使用await關(guān)鍵字,獲取Promise對象"成功狀態(tài)"結(jié)果值* 注意:await必須用在async修飾的函數(shù)內(nèi)(await會阻止"異步函數(shù)內(nèi)"代碼繼續(xù)執(zhí)行,原地等待結(jié)果)*///  1.定義async修飾函數(shù)async function getData(){try {/*要執(zhí)行的代碼*/const pObj = await axios({url:'http://hmajax.itheima.net/api/province'})const pname = pObj.data.list[0]const cObj = await axios({url:'http://hmajax.itheima.net/api/city',params:{pname}})const cname = cObj.data.list[0]const aObj = await axios({url:'http://hmajax.itheima.net/api/area1',params:{pname,cname}})const areaName = aObj.data.list[0]document.querySelector('.province').innerHTML = pnamedocument.querySelector('.city').innerHTML = cnamedocument.querySelector('.area').innerHTML = areaName} catch (error) {/* error接收的是,錯誤信息try里代碼,如果有錯誤,直接進入這里執(zhí)行*/console.dir(error);}}getData()</script>

在這里插入圖片描述

在這里插入圖片描述

事件循環(huán)(EventLoop)

概念:JavaScript 有一個基于事件循環(huán)的并發(fā)模型,事件循環(huán)負(fù)責(zé)執(zhí)行代碼、收集和處理事件以及執(zhí)行隊列中的子任務(wù)。這個模型與其他語言中的模型截然不同,比如 C 和 Java。
原因;JavaScript單線程(某一時刻只能執(zhí)行一行代碼),為了讓耗時代碼不阻塞其他代碼運行,設(shè)計了事件循環(huán)模型。
JavaScript內(nèi)代碼如何執(zhí)行?

1.執(zhí)行同步代碼,遇到異步代碼交給宿主瀏覽器環(huán)境執(zhí)行
2.異步有了結(jié)果后,把回調(diào)函數(shù)放入任務(wù)隊列排隊
3.當(dāng)調(diào)用??臻e后,反復(fù)調(diào)用任務(wù)隊列里的回調(diào)函數(shù)

 <script>/*** 目標(biāo):閱讀并回答執(zhí)行的順序結(jié)果*/console.log(1)setTimeout(() => {console.log(2)}, 0)console.log(3)setTimeout(() => {console.log(4)}, 2000)console.log(5)</script>

事件循環(huán)練習(xí)

 <script>/*** 目標(biāo):閱讀并回答執(zhí)行的順序結(jié)果* 1 5 3 2 4 6(點擊時觸發(fā))*/console.log(1)setTimeout(() => {console.log(2)}, 0)function myFn() {console.log(3)}function ajaxFn() {const xhr = new XMLHttpRequest()xhr.open('GET', 'http://hmajax.itheima.net/api/province')xhr.addEventListener('loadend', () => {console.log(4)})xhr.send()}for (let i = 0; i < 1; i++) {console.log(5)}ajaxFn()document.addEventListener('click', () => {console.log(6)})myFn()</script>

事件·循環(huán)·練習(xí)

宏任務(wù)與微任務(wù)-執(zhí)行任務(wù)

宏任務(wù) :瀏覽器執(zhí)行的異步代碼,例如:JS執(zhí)行腳本事件,setTimeout/setInterval,AJAX請求完成事件,用戶交互事件等。

微任務(wù):JS引擎執(zhí)行的異步代碼,例如:Promise對象.then()的回調(diào)
JavaScript內(nèi)代碼如何執(zhí)行?

1.執(zhí)行第一個script腳本時間宏任務(wù),里面同步代碼
2.遇到宏任務(wù)/微任務(wù)交給宿主環(huán)境,有結(jié)果回調(diào)函數(shù)進入對應(yīng)隊列
當(dāng)執(zhí)行棧空閑時,清空微任務(wù)隊列,再執(zhí)行下一個宏任務(wù),從1再來

  <script>// 目標(biāo):回答代碼執(zhí)行順序console.log(1)setTimeout(() => {console.log(2)const p = new Promise(resolve => resolve(3))p.then(result => console.log(result))}, 0)const p = new Promise(resolve => {setTimeout(() => {console.log(4)}, 0)resolve(5)})p.then(result => console.log(result))const p2 = new Promise(resolve => resolve(6))p2.then(result => console.log(result))console.log(7)</script>

事件循環(huán)-執(zhí)行過程

Promise.all靜態(tài)方法

概念:合并多個Promise對象,等待所有提示成功完成(或某一個失敗),做后續(xù)邏輯

在這里插入圖片描述

 <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>/*** 目標(biāo):掌握Promise的all方法作用,和使用場景* 業(yè)務(wù):當(dāng)我需要同一時間顯示多個請求的結(jié)果時,就要把多請求合并* 例如:默認(rèn)顯示"北京", "上海", "廣州", "深圳"的天氣在首頁查看* code:* 北京-110100* 上海-310100* 廣州-440100* 深圳-440300*///  1.請求城市天氣,得到Promise對象const bjObj = axios({url:'http://hmajax.itheima.net/api/weather',params:{city:'110100'}})const shObj = axios({url:'http://hmajax.itheima.net/api/weather',params:{city:'310100'}})const gzObj = axios({url:'http://hmajax.itheima.net/api/weather',params:{city:'440100'}})const szObj = axios({url:'http://hmajax.itheima.net/api/weather',params:{city:'440300'}})//  console.log(bjObj,shObj, gzObj,szObj);// 2.使用 Promise.all,合并對各Promise對象const p = Promise.all([bjObj,shObj, gzObj,szObj])p.then(result => {console.log(result);// 注意:結(jié)果數(shù)組順序和合并時順序是一致的const htmlStr = result.map(item => {// 解構(gòu)賦值const {area,weather}=item.data.datareturn `<li>${area}-----${weather}</li>`  }).join('')document.querySelector('.my-ul').innerHTML = htmlStr}).catch(error => {console.dir(eerror)})</script>

商品分類

   目標(biāo):把所有商品分類“同時”渲染到頁面上1. 獲取所有一級分類數(shù)據(jù)2. 遍歷id,創(chuàng)建獲取二級分類請求3. 合并所有二級分類Promise對象4. 等待同時成功后,渲染頁面
 <script>// 1. 獲取所有一級分類數(shù)據(jù)axios({url:'http://hmajax.itheima.net/api/category/top'}).then(result => {console.log(result);// 2. 遍歷id,創(chuàng)建獲取二級分類請求const promiseList = result.data.data.map(item =>{return axios({url:'http://hmajax.itheima.net/api/category/sub',params:{id:item.id}})})console.log(promiseList);// 3. 合并所有二級分類Promise對象const p = Promise.all(promiseList)p.then(result => {console.log(result);// 4. 等待同時成功后,渲染頁面const htmlStr = result.map(item => {const obj = item.data.datareturn`<div class="item"><h3>一級分類名字:${obj.name}</h3><ul>${obj.children.map(item => {return `  <li><a href="javascript:;"><img src=${item.picture}"><p>${item.name}</p></a></li>`}).join('')}</ul></div>`}).join('')document.querySelector('.sub-list').innerHTML = htmlStr})})</script>

在這里插入圖片描述

學(xué)習(xí)反饋

 目標(biāo)1:完成省市區(qū)下拉列表切換1.1 設(shè)置省份下拉菜單數(shù)據(jù)1.2 切換省份,設(shè)置城市下拉菜單數(shù)據(jù),清空地區(qū)下拉菜單1.3 切換城市,設(shè)置地區(qū)下拉菜單數(shù)據(jù)

在這里插入圖片描述

在這里插入圖片描述
在這里插入圖片描述

  目標(biāo)2:收集數(shù)據(jù)保存2.1 監(jiān)聽提交的點擊事件2.2 依靠插件收集表單數(shù)據(jù)2.3 基于axios提交保存

在這里插入圖片描述

/*** 目標(biāo)1:完成省市區(qū)下拉列表切換*  1.1 設(shè)置省份下拉菜單數(shù)據(jù)*  1.2 切換省份,設(shè)置城市下拉菜單數(shù)據(jù),清空地區(qū)下拉菜單*  1.3 切換城市,設(shè)置地區(qū)下拉菜單數(shù)據(jù)*/
// 1.1 設(shè)置省份下拉菜單數(shù)據(jù)
axios({url:'http://hmajax.itheima.net/api/province'}).then(result => {const optionStr = result.data.list.map(item => {return `  <option value="${item}">${item}</option>`}).join('')document.querySelector('.province').innerHTML=`<option value="">省份</option>`+optionStr
})// 1.2 切換省份,設(shè)置城市下拉菜單數(shù)據(jù),清空地區(qū)下拉菜單
document.querySelector('.province').addEventListener('change',async e => {// 獲取用戶選擇的省份名字console.log(e.target.value);const result = await axios({url:'http://hmajax.itheima.net/api/city',params:{pname:e.target.value}}).then(result =>{const optionStr = result.data.list.map(item => {return `  <option value="${item}">${item}</option>`}).join('')// 把默認(rèn)初始選項+下屬城市數(shù)據(jù)插入select中   document.querySelector('.city').innerHTML=`<option value="">城市</option>`+optionStr //    清空地區(qū)數(shù)據(jù)document.querySelector('.area').innerHTML= `<option value="">地區(qū)</option>`})
})// 1.3 切換城市,設(shè)置地區(qū)下拉菜單數(shù)據(jù)document.querySelector('.city').addEventListener('change',async e => {console.log(e.target.value);const result = await axios({url:'http://hmajax.itheima.net/api/area',params:{pname: document.querySelector('.province').value,cname:e.target.value}}).then(result =>{const optionStr = result.data.list.map(item => {return `  <option value="${item}">${item}</option>`}).join('')document.querySelector('.area').innerHTML=`<option value="">地區(qū)</option>`+optionStr })
})
/* 目標(biāo)2:收集數(shù)據(jù)保存2.1 監(jiān)聽提交的點擊事件2.2 依靠插件收集表單數(shù)據(jù)2.3 基于axios提交保存
*/
// 2.1 監(jiān)聽提交的點擊事件
document.querySelector('.submit').addEventListener('click',async ()=> {// 2.2 依靠插件收集表單數(shù)據(jù)const form =document.querySelector('.info-form')const data = serialize(form,{hash:true,empty:true})console.log(data);// 2.3 基于axios提交保存try {const result = await axios({url:'http://hmajax.itheima.net/api/feedback',method:'post',data })console.log(result);alert(result.data.message)} catch (error) {console.dir(error);alert(error.response.data.message)}})

總結(jié)

學(xué)習(xí)了這門課程,AJAX的大概知識我都清楚了,也在學(xué)習(xí)過程中,我得到了一些學(xué)習(xí)經(jīng)驗,比如,看完一天的視頻,要回去復(fù)習(xí),不然容易忘記,邊看視頻邊敲代碼邊理解或者看完一天視頻再敲代碼,可能帶著回憶的狀態(tài),這樣子可以檢驗自己是否真的懂(可能這個方法會好一點,因人而異),還有就是代碼也不是敲一遍就行的,最多敲三遍,最后一遍一定是自己明白了,在不借助外力的情況下,自己敲(雖然但是,我還沒達到那種境界,在努力中)。
最后送大家一句話:博學(xué)之,審問之,慎思之,明辨之,篤行之。

http://www.risenshineclean.com/news/29880.html

相關(guān)文章:

  • 福建省建設(shè)執(zhí)業(yè)繼續(xù)教育網(wǎng)站吉林seo排名公司
  • 浙江融興建設(shè)有限公司網(wǎng)站網(wǎng)站建設(shè)公司推薦
  • 大學(xué)生網(wǎng)站建設(shè)方案世界球隊最新排名
  • 網(wǎng)站建設(shè)有增值稅發(fā)票嗎seo個人優(yōu)化方案案例
  • 夏天做啥網(wǎng)站能致富sem優(yōu)化師
  • 網(wǎng)站制作網(wǎng)站建設(shè)需要多少錢網(wǎng)站銷售怎么推廣
  • 教做家庭菜的網(wǎng)站怎么做推廣比較成功
  • 樂清做網(wǎng)站價格推廣的軟件
  • 彈幕網(wǎng)站是怎么做的發(fā)布軟文平臺
  • seo網(wǎng)站建設(shè)價格自己怎么創(chuàng)建網(wǎng)站
  • 商貿(mào)網(wǎng)站管理培訓(xùn)機構(gòu)
  • ftp是專門提供文件傳輸?shù)木W(wǎng)站百度注冊新賬號
  • 品牌seo公司焦作關(guān)鍵詞優(yōu)化排名
  • 建網(wǎng)站的服務(wù)器學(xué)電商出來一般干什么工作
  • 創(chuàng)意個人網(wǎng)站設(shè)計大冶seo網(wǎng)站優(yōu)化排名推薦
  • 律師網(wǎng)站深圳網(wǎng)站設(shè)計百度app在哪里找
  • 黔東南網(wǎng)頁設(shè)計seo搜索引擎優(yōu)化人員
  • wordpress掃碼收款seo網(wǎng)絡(luò)營銷課程
  • 公司做的網(wǎng)站賬務(wù)處理淘寶關(guān)鍵詞搜索量查詢
  • 開發(fā)公司人效比seo排名培訓(xùn)學(xué)校
  • 做網(wǎng)站彩票代理犯法嗎我是站長網(wǎng)
  • php做網(wǎng)站網(wǎng)絡(luò)營銷有什么崗位
  • 國內(nèi)可以做的國外兼職網(wǎng)站海外營銷方案
  • 專門做微信推送的網(wǎng)站搜索引擎優(yōu)化要考慮哪些方面?
  • 海北高端網(wǎng)站建設(shè)哪家好網(wǎng)站推廣途徑和推廣要點
  • 網(wǎng)站建設(shè)方案書深圳關(guān)鍵詞推廣優(yōu)化
  • 東營本地網(wǎng)站制作公司可以入侵的網(wǎng)站
  • 公司網(wǎng)站維護該誰來做全網(wǎng)營銷外包
  • java可以做微信網(wǎng)站么站長統(tǒng)計工具
  • 做域名后就得做網(wǎng)站嗎河北高端網(wǎng)站建設(shè)