Ajax_01筆記
前置知識(shí)點(diǎn)
在JavaScript中
問(wèn)題1:將數(shù)組轉(zhuǎn)為字符串,以及字符串轉(zhuǎn)為數(shù)組的方式。
問(wèn)題2、將對(duì)象轉(zhuǎn)為字符串,以及字符串轉(zhuǎn)為對(duì)象的方法。
方法:
問(wèn)題1:
- 將數(shù)組轉(zhuǎn)為字符串可以使用
join()
方法。例如:var array = [1, 2, 3]; var str = array.join(',');
,將數(shù)組[1, 2, 3]
轉(zhuǎn)為字符串"1,2,3"
。- 將字符串轉(zhuǎn)為數(shù)組可以使用
split()
方法。例如:var str = "1,2,3"; var array = str.split(',');
,將字符串"1,2,3"
轉(zhuǎn)為數(shù)組[1, 2, 3]
。問(wèn)題2:
- 將對(duì)象轉(zhuǎn)為字符串可以使用
JSON.stringify()
方法。例如:var obj = {name: "John", age: 25}; var str = JSON.stringify(obj);
,將對(duì)象{name: "John", age: 25}
轉(zhuǎn)為字符串"{\"name\":\"John\",\"age\":25}"
。- 將字符串轉(zhuǎn)為對(duì)象可以使用
JSON.parse()
方法。例如:var str = "{\"name\":\"John\",\"age\":25}"; var obj = JSON.parse(str);
,將字符串"{\"name\":\"John\",\"age\":25}"
轉(zhuǎn)為對(duì)象{name: "John", age: 25}
。請(qǐng)注意,字符串必須符合 JSON 格式的要求。
01_什么是Ajax和axios使用
定義
- Ajax(Asynchronous JavaScript and XML)是一種用于創(chuàng)建交互式Web應(yīng)用程序的技術(shù)。它通過(guò)在不重新加載整個(gè)頁(yè)面的情況下與服務(wù)器通信,實(shí)現(xiàn)異步數(shù)據(jù)傳輸和更新。使用Ajax,可以在用戶(hù)與網(wǎng)頁(yè)交互時(shí),向服務(wù)器發(fā)送請(qǐng)求并接收響應(yīng),然后使用JavaScript動(dòng)態(tài)更新頁(yè)面的部分內(nèi)容。這樣可以提供更流暢和高效的用戶(hù)體驗(yàn),減少了不必要的頁(yè)面刷新。Ajax廣泛用于創(chuàng)建各種Web應(yīng)用,如動(dòng)態(tài)表單驗(yàn)證、自動(dòng)補(bǔ)全搜索、實(shí)時(shí)更新等。它基于Web標(biāo)準(zhǔn)技術(shù),包括HTML、CSS、JavaScript和XML/JSON數(shù)據(jù)格式。
怎么學(xué)習(xí)Ajax?
- 先使用axios庫(kù),與服務(wù)器進(jìn)行數(shù)據(jù)通行。
- 基于XMLHttpRequest封裝、代碼簡(jiǎn)單使用次數(shù)高。
- Vue、React項(xiàng)目中都會(huì)用到axios。
- 在學(xué)習(xí)XMLHttpRequest對(duì)象的使用,了解Ajax底層原理。
axios的使用
語(yǔ)法:
引入axios.js官方庫(kù)地址 : https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js 得到一個(gè)全局的axios函數(shù)。
使用axios函數(shù):
- 傳入配置對(duì)象。
- 在用.then回調(diào)函數(shù)接收服務(wù)器返回的結(jié)果,并做出后續(xù)處理。
代碼示例
需求:請(qǐng)求目標(biāo)資源地址,拿到省份列表數(shù)據(jù),顯示到頁(yè)面。
目標(biāo)資源地址:http://hmajax.itheima.net/api/province
<body> <!-- axios庫(kù)地址: https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js 省份數(shù)據(jù)地址: http://ajax-api.itheima.net/api/province 目標(biāo):使用axios庫(kù),獲取省份列表數(shù)據(jù),展示到頁(yè)面上 --> <p class="isP"></p> <!-- 引入axios庫(kù) --> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> // 引入后得到一個(gè)axios函數(shù),并使用axios函數(shù) axios({ // 資源路徑地址 url: 'http://ajax-api.itheima.net/api/province' }).then(result => { //result為回調(diào)函數(shù)的形參 // 查看服務(wù)器返回的調(diào)函數(shù) console.log(result) // 查看返回值里面的內(nèi)容 console.log(result.data.data) // 查看返回中message的返回狀態(tài) console.log(result.data.message) // 將返回的數(shù)組轉(zhuǎn)為字符串 console.log(result.data.data.join('<br>')) // 插入到標(biāo)簽容器中,渲染視圖 document.querySelector('.isP').innerHTML = result.data.data.join('<br>') }) </script> </body>
02_認(rèn)識(shí)URL
URL:統(tǒng)一資源定位符,簡(jiǎn)稱(chēng)網(wǎng)址,用于訪問(wèn)網(wǎng)絡(luò)上的資源。
新聞數(shù)據(jù)地址: http://hmajax.itheima.net/api/news
- http是協(xié)議
- hmajax.itheima.net是域名
- api/news是資源路徑地址
03_查詢(xún)參數(shù)
params查詢(xún)參數(shù)
- params是一個(gè)查詢(xún)參數(shù)對(duì)象:語(yǔ)法格式為params: {參數(shù)名:值} 。參數(shù)名是接口文檔中提供的。
-
作用:使用查詢(xún)參數(shù)提供額外信息,獲取對(duì)應(yīng)的數(shù)據(jù)。
使用params ,里面添加攜帶的參數(shù)名和參數(shù)值即可。
-
代碼演示
<p></p> <!-- 城市列表: http://hmajax.itheima.net/api/city 參數(shù)名: pname 值: 省份名字 --> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> axios({ url: 'http://hmajax.itheima.net/api/city', // 攜帶查詢(xún)參數(shù) params: { pname: '浙江省' //后期這里輸入的查詢(xún)值就是讓 用戶(hù)輸入的。 } }).then(result => { console.log(result.data.list) document.querySelector('p').innerHTML = result.data.list.join('<br>') }) </script>
04_查詢(xún)地區(qū)案例
- 需求:根據(jù)用戶(hù)輸入的省份和市區(qū),查詢(xún)?cè)撌袇^(qū)的數(shù)據(jù),并渲染到容器視圖中。
代碼示例
<script> /* 獲取地區(qū)列表: http://hmajax.itheima.net/api/area 查詢(xún)參數(shù): pname: 省份或直轄市名字 cname: 城市名字 */ // 獲取用戶(hù)需要查詢(xún)的內(nèi)容值 const province = document.querySelector('.province') const city = document.querySelector('.city') // 1、這個(gè)模塊功能是從用戶(hù)點(diǎn)擊事件開(kāi)始,所以先綁定點(diǎn)擊事件 document.querySelector('.sel-btn').addEventListener('click', () => { // 2、點(diǎn)擊完后,就執(zhí)行axios函數(shù) axios({ // 3、向服務(wù)器發(fā)送查詢(xún)請(qǐng)求 url: 'http://hmajax.itheima.net/api/area', // 4、攜帶用戶(hù)輸入的查詢(xún)參數(shù) params: { pname: province.value, cname: city.value } }).then(result => { console.log(result.data.list) console.log(result.data.message) const list = result.data.list // 5、將返回的數(shù)組使用map方法操作插入到標(biāo)簽中然后返回新的數(shù)組,將新的數(shù)組轉(zhuǎn)為字符串形式 const res = list.map(item => `<li class="list-group-item">${item}</li>`).join('') //得到了操作后的新數(shù)組,在轉(zhuǎn)字符串 // 6、 將map返回的新數(shù)組插入到頁(yè)面視圖中 document.querySelector('.list-group').innerHTML = res console.log(res) }) }) </script>
map語(yǔ)句的詳細(xì)解釋:
首先,我們有一個(gè)
res
數(shù)組。通過(guò)map
方法,對(duì)數(shù)組中的每個(gè)元素進(jìn)行處理。箭頭函數(shù)表達(dá)式(item =>
- ${item}
)
接收一個(gè)參數(shù)item
,并返回一個(gè)字符串模板,生成一個(gè)帶有item
值的<li>
元素。然后,通過(guò)
join('')
方法將所有處理后的字符串連接在一起,形成一個(gè)字符串。最終,我們得到一個(gè)名為
theLi
的字符串,其中包含了循環(huán)處理后的<li>
元素。
05_常用請(qǐng)求方法和數(shù)據(jù)提交
method: 請(qǐng)求方法,GET可以省略不寫(xiě)(不區(qū)分大小寫(xiě))
data:提交數(shù)據(jù)
需求: 注冊(cè)用戶(hù): url: 'http://hmajax.itheima.net/api/register,
請(qǐng)求方法: POST
參數(shù)名:
? username: 用戶(hù)名 (中英文和數(shù)字組成, 最少8位)
? password: 密碼 (最少6位)
目標(biāo): 點(diǎn)擊按鈕, 通過(guò)axios提交用戶(hù)和密碼, 完成注冊(cè)
代碼示例
// 1、注冊(cè)點(diǎn)擊事件 document.querySelector('.btn').addEventListener('click', () => { // 2、使用axios函數(shù)發(fā)送請(qǐng)求 axios({ url: 'http://hmajax.itheima.net/api/register', // 3、聲明請(qǐng)求方法 method: 'POST', // 4、提交數(shù)據(jù) data: { username: 'itheima007', password: '7654321' } }).then(result => { // 5、查看瀏覽器響應(yīng)的結(jié)果 // 瀏覽器響應(yīng)狀態(tài)信息 console.log(result.data.message) //無(wú)賬號(hào) console.log(result.data) }) })
需要提交數(shù)據(jù),就得使用post 同時(shí)使用data攜帶需要提交的參數(shù) (params是查詢(xún)的參數(shù),不要混淆了)
06_axios錯(cuò)誤處理
在then方法后面寫(xiě)一個(gè)catch方法,傳入回調(diào)函數(shù)并定義形參
代碼示例
.then(result => {
console.log(result)
}).catch(error => {
// 錯(cuò)誤信息處理
console.log(error)
console.log(error.response.data.message)
})
console.log(error.response.data.message) 就能得到具體的錯(cuò)誤信息
我們可以將返回的信息通過(guò)彈窗返回給用戶(hù)
07_HTTP協(xié)議-請(qǐng)求報(bào)文
http協(xié)議:規(guī)定了瀏覽器發(fā)送及服務(wù)器返回內(nèi)容的格式。
請(qǐng)求報(bào)文
請(qǐng)求報(bào)文:瀏覽器按照http協(xié)議要求的格式,發(fā)送給服務(wù)器的內(nèi)容(就是axios里面的內(nèi)容)。
請(qǐng)求報(bào)文的組成
- 請(qǐng)求行:請(qǐng)求方法、URL、協(xié)議
- 請(qǐng)求頭:以鍵值對(duì)的格式攜帶的附加信息,比如:Content-Type
- 空行:分隔請(qǐng)求頭,空行之后的是發(fā)送給服務(wù)器的資源
- 請(qǐng)求體:發(fā)送的資源
通過(guò)chrome 開(kāi)發(fā)者工具中的網(wǎng)絡(luò)來(lái)進(jìn)行查看
08_請(qǐng)求報(bào)文-錯(cuò)誤排查
在保證自己測(cè)試沒(méi)問(wèn)題的時(shí)候,使用開(kāi)發(fā)者工具中的網(wǎng)絡(luò)選項(xiàng)卡進(jìn)行查看我們報(bào)錯(cuò)的信息,觀察后對(duì)代碼進(jìn)行改進(jìn)(這樣精確定位提高效率)
09_HTTP協(xié)議-響應(yīng)報(bào)文
http協(xié)議:規(guī)定了瀏覽器發(fā)送及服務(wù)器返回內(nèi)容的格式。
響應(yīng)報(bào)文
- 響應(yīng)報(bào)文:服務(wù)器按照http協(xié)議要求的格式,返回非瀏覽器的內(nèi)容
響應(yīng)報(bào)文的組成
- 響應(yīng)行:(狀態(tài)行):協(xié)議、http響應(yīng)狀態(tài)碼,返回給瀏覽器的內(nèi)容
- 響應(yīng)頭:以鍵值對(duì)的格式攜帶的附加信息,比如:Content-Type
- 空行:分隔請(qǐng)求頭,空行之后的是發(fā)送給服務(wù)器的資源
- 響應(yīng)體:返回的資源
響應(yīng)狀態(tài)碼
狀態(tài)碼 | 說(shuō)明 |
---|---|
1xx | 信息 |
2xx | 成功 |
3xx | 重定向消息 |
4xx | 客戶(hù)端錯(cuò)誤 |
5xx | 服務(wù)端錯(cuò)誤 |
例如;404表示(服務(wù)器找不到資源)
可以再網(wǎng)絡(luò)中的響應(yīng)中查看服務(wù)器相應(yīng)的結(jié)果
10_接口文檔
接口文檔:描述接口的文章
接口:使用Ajax和服務(wù)器通訊時(shí),使用的URL,請(qǐng)求方法,以及參數(shù)。
重點(diǎn):就是在于學(xué)會(huì)看著接口文檔的需求來(lái)編寫(xiě)代碼。
11_用戶(hù)登錄案例
需求
- 點(diǎn)擊登錄時(shí),判斷用戶(hù)名和密碼長(zhǎng)度
- 提交數(shù)據(jù)和服務(wù)通信
- 響應(yīng)提示消息渲染
代碼示例
<script> // 目標(biāo)1:點(diǎn)擊登錄時(shí),用戶(hù)名和密碼長(zhǎng)度判斷,并提交數(shù)據(jù)和服務(wù)器通信 document.querySelector('.btn-login').addEventListener('click', () => { // 1、獲取用戶(hù)名和密碼框以及value值 const username = document.querySelector('.username').value const password = document.querySelector('.password').value console.log(username,password) // 2、點(diǎn)擊登錄時(shí),判斷用戶(hù)名和密碼長(zhǎng)度 if (username.length < 8 || username.length > 16) { alert('用戶(hù)名不合法') return } else if (password.length < 6 || password.length > 16) { alert('密碼不合法') return } else { axios({ url: 'http://hmajax.itheima.net/api/login', method: 'post', data: { username, password } }).then((result) => { // 返回服務(wù)器響應(yīng)的狀態(tài) alert(result.data.message) }).catch((error) => { // 返會(huì)服務(wù)器響應(yīng)的錯(cuò)誤信息 alert(error.response.data.message) }) } }) </script>
優(yōu)化提示框后的代碼
直接上代碼
<script> // 目標(biāo)1:點(diǎn)擊登錄時(shí),用戶(hù)名和密碼長(zhǎng)度判斷,并提交數(shù)據(jù)和服務(wù)器通信 // 目標(biāo)2:使用提示框,反饋提示消息 /* * 提示框需求分析 * 1、獲取提示框標(biāo)簽 * 2、封裝一個(gè)函數(shù),用于渲染視圖。 * 3、設(shè)置提示文字,以及對(duì)應(yīng)的顏色,成功為綠色,失敗為紅色 * 4、為了讓提示框自動(dòng)隱藏,我們添加一個(gè)延遲函數(shù) */ // 1.獲取提示框標(biāo)簽 const Alert = document.querySelector('.alert-success') function getAlert(message, flag) { // 3.設(shè)置提示文字,以及對(duì)應(yīng)的顏色 Alert.innerHTML = message Alert.classList.add('show') // flag ? 'alert-succes' : 'alert-danger' // console.log(flag ? 'alert-succes' : 'alert-danger') Alert.classList.add(flag ? 'alert-succes' : 'alert-danger') // 4.聲明一個(gè)延遲函數(shù),用于一定事件后隱藏提示框(也就是移除類(lèi)名) setTimeout(() => { Alert.classList.remove('show') // 提示框顏色類(lèi)名重置,也就是本次使用完清除 Alert.classList.remove(flag ? 'alert-succes' : 'alert-danger') }, 2000) } // 1.1 登錄-點(diǎn)擊事件 document.querySelector('.btn-login').addEventListener('click', () => { // 1.2 獲取用戶(hù)名和密碼 const username = document.querySelector('.username').value const password = document.querySelector('.password').value // console.log(username, password) // 1.3 判斷長(zhǎng)度 if (username.length < 8) { // 調(diào)用函數(shù),渲染當(dāng)前提示信息 getAlert('用戶(hù)名必須大于等于8位', false) console.log('用戶(hù)名必須大于等于8位') return // 阻止代碼繼續(xù)執(zhí)行 } if (password.length < 6) { // 調(diào)用函數(shù)渲染當(dāng)前提示信息 getAlert('密碼必須大于等于6位', false) console.log('密碼必須大于等于6位') return // 阻止代碼繼續(xù)執(zhí)行 } // 1.4 基于axios提交用戶(hù)名和密碼 // console.log('提交數(shù)據(jù)到服務(wù)器') axios({ url: 'http://hmajax.itheima.net/api/login', method: 'POST', data: { username, password } }).then(result => { // 調(diào)用提示框渲染函數(shù),然后將返回值當(dāng)做實(shí)參 getAlert(result.data.message,true) console.log(result) console.log(result.data.message) }).catch(error => { // 調(diào)用提示框渲染函數(shù),然后將返回值當(dāng)做實(shí)參 getAlert(error.response.data.message,false) console.log(error) console.log(error.response.data.message) }) }) </script>
12_form-serialize插件使用
作用:
作用: 快速收集表單元素的值
語(yǔ)法
語(yǔ)法: const data = serialize(form,{hash: true,empty: true})
- serialize函數(shù)里面的form可以獲得表單中所有name屬性標(biāo)簽的值
- 把插件引入到自己的網(wǎng)頁(yè)中
2、 使用serialize函數(shù),快速收集表單元素的值
參數(shù)1、需要獲取哪個(gè)表單的數(shù)據(jù)
表單元素設(shè)置 name 屬性,值會(huì)作為對(duì)象的屬性名
建議 name 屬性的值,最好和接口文檔參數(shù)名一致
參數(shù)2、配置對(duì)象
- hash 設(shè)置獲取數(shù)據(jù)結(jié)構(gòu)
true: js對(duì)象 (推薦使用true,因?yàn)閷@得的對(duì)象可以提交給服務(wù)器)
false: 查詢(xún)字符串
- empty 設(shè)置是否取空值
true: 獲取空值(推薦)
false: 不獲取空值
目標(biāo)
目標(biāo):在點(diǎn)擊提交時(shí),使用form-serialize插件,快速收集表單元素值
代碼示例
<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> <!-- 引入serizlize插件 --> <script src="../lib/form-serialize.js"></script> <script> //獲取按鈕標(biāo)簽,注冊(cè)點(diǎn)擊事件 document.querySelector('.btn').addEventListener('click', () => { const form = document.querySelector('.example-form') const data = serialize(form,{hash: true,empty: true}) //寫(xiě)這種即可哦 // const data = serialize(form,{hash: false ,empty: true}) // const data = serialize(form,{hash: false ,empty: true}) console.log(data) }) </script>
- 對(duì)參數(shù)有問(wèn)題可以看上面的語(yǔ)法
serialize案例
使用插件替代原生js 獲取元素的寫(xiě)法。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-621573.html
代碼演示
將serialize獲取到的js對(duì)象,通過(guò) 對(duì)象解構(gòu) 拿到里面的值。然后直接傳遞給axios函數(shù)里面的提交數(shù)據(jù)給服務(wù)器文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-621573.html
// 3.1 使用serialize插件 const form = document.querySelector('.form') const data = serialize(form, { hash: true, empty: true }) console.log(data) //{username: 'itheima007', password: '7654321'} // 3.2 利用對(duì)象 解構(gòu) 進(jìn)行取值 由于屬性名和屬性值相同,此處簡(jiǎn)寫(xiě) const { username, password} = data // 1.2 獲取用戶(hù)名和密碼 // const username = document.querySelector('.username').value // const password = document.querySelector('.password').value console.log(username, password)
- serialize函數(shù)里面的form可以獲得表單中所有name屬性標(biāo)簽的值
到了這里,關(guān)于Ajax筆記_01(知識(shí)點(diǎn)、包含代碼和詳細(xì)解析)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!