出口貿(mào)易網(wǎng)站網(wǎng)站推廣工具有哪些
目錄
1.XMLHttpRequest
1.1?XMLHttpRequest認識
1.2 用ajax發(fā)送請求
1.3 案例
1.4?XMLHttpRequest - 查詢參數(shù)
1.5 XMLHttpRequest - 數(shù)據(jù)提交
2.Promise
2.1?Promise認識
2.2?Promise - 三種狀態(tài)
2.3 案例
3.封裝簡易版 axios
3.1 封裝_簡易axios_獲取省份列表
3.2 封裝_簡易axios_獲取地區(qū)列表
3.3?封裝_簡易axios_注冊用戶
4.案例 - 天氣預報
4.1 天氣預報 - 獲取并渲染城市天氣
4.2?天氣預報 - 搜索城市列表
4.2 天氣預報 - 展示城市天氣
學習之前先了解一下ajax和axios之間的區(qū)別
-
Ajax:是一種允許網(wǎng)頁在后臺與服務器進行數(shù)據(jù)交換的技術,而不需要重新加載整個頁面。它不是一種特定的庫或框架,而是一種實現(xiàn)異步數(shù)據(jù)傳輸?shù)耐ㄓ梅椒ā?strong>Ajax通常使用 XMLHttpRequest 對象來發(fā)起 HTTP 請求。
-
Axios:是一個基于 promise 的 HTTP 客戶端,它適用于瀏覽器和 node.js。它提供了更加簡潔的 API,以方便發(fā)送 HTTP 請求。Axios 的底層實現(xiàn)仍然依賴于 XMLHttpRequest(在瀏覽器中)或 node.js 的原生 HTTP 模塊,但它抽象了它們的復雜性,使得發(fā)送請求更加容易。
在現(xiàn)代前端開發(fā)中,Axios 被廣泛推薦用來發(fā)起 HTTP 請求,因為它簡單易用,并且容易集成到常見的進程式任務中,如 React、Vue 或 Angular 應用。
1.XMLHttpRequest
1.1?XMLHttpRequest認識
XMLHttpRequest
?是一種在網(wǎng)頁上執(zhí)行異步請求的 API,它允許你在不重新加載整個頁面的情況下與服務器交換數(shù)據(jù)。它廣泛用于實現(xiàn) AJAX(Asynchronous JavaScript and XML)功能,從而使網(wǎng)頁能夠動態(tài)更新內容
關系:axios 內部采用 XMLHttpRequest 與服務器交互
1.2 用ajax發(fā)送請求
- 1. 創(chuàng)建 XMLHttpRequest 對象
- 2. 配置請求方法和請求 url 地址
- 3. 監(jiān)聽 loadend 事件,接收響應結果
- 4. 發(fā)起請求
1.3 案例

代碼:
<body><p></p><script>/*** 目標:使用XHR攜帶查詢參數(shù),展示某個省下屬的城市列表*/const p = document.querySelector('p')/* 步驟:1. 創(chuàng)建 XMLHttpRequest 對象2. 配置請求方法和請求 url 地址3. 監(jiān)聽 loadend 事件,接收響應結果4. 發(fā)起請求 */const xml = new XMLHttpRequest()xml.open('GET', 'http://hmajax.itheima.net/api/city?pname=遼寧省')xml.addEventListener('loadend', function () {// {"message":"獲取城市成功","list":["沈陽市","大連市"]}console.log(xml.response)// 將json字符串轉換為對象const data = JSON.parse(xml.response)console.log(data.list.join('<br>'))p.innerHTML = data.list.join('<br>')})xml.send()</script>
</body>
1.4?XMLHttpRequest - 查詢參數(shù)
1.5 XMLHttpRequest - 數(shù)據(jù)提交

- 請求頭設置 Content-Type:application/json
- 請求體攜帶 JSON 字符串
代碼:
<body><button class="reg-btn">注冊用戶</button><script>/*** 目標:使用xhr進行數(shù)據(jù)提交-完成注冊功能*//*** 需求:通過 XHR 提交用戶名和密碼,完成注冊功能核心:請求頭設置 Content-Type:application/json請求體攜帶 JSON 字符串*/document.querySelector('.reg-btn').addEventListener('click', () => {const xml = new XMLHttpRequest()xml.open('POST', 'http://hmajax.itheima.net/api/register')xml.addEventListener('loadend', function () {console.log(xml.response)})// 讓瀏覽器知道,傳遞的數(shù)據(jù)是json字符串xml.setRequestHeader('Content-Type', 'application/json')const obj = {username: 'linhanxin',password: '1234567'}// 轉為JSON字符串const data = JSON.stringify(obj)// 發(fā)送請求體的數(shù)據(jù)xml.send(data)})</script>
</body>
2.Promise
2.1?Promise認識
promise對象用于表示一個異步操作的最終完成(或失敗)及其結果值的對象。
- 1. 邏輯更清晰
- 2. 了解 axios 函數(shù)內部運作機制,以及簡化 ajax的開發(fā)
- 3. 能解決回調函數(shù)地獄問題
當你使用?axios
?發(fā)起 HTTP 請求時,它會返回一個?Promise
?對象,這個?Promise
?對象會在請求完成時解決(resolve)或拒絕(reject)。


2.2?Promise - 三種狀態(tài)
- ? 待定(pending) :初始狀態(tài),既沒有被兌現(xiàn),也沒有被拒絕
- ? 已兌現(xiàn)(fulfilled) :意味著,操作成功完成
- ? 已拒絕(rejected) :意味著,操作失敗
2.3 案例
- 1. 創(chuàng)建 Promise 對象
- 2. 執(zhí)行 XHR 異步代碼,獲取省份列表
- 3. 關聯(lián)成功或失敗函數(shù),做后續(xù)處理
效果圖:

<!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>案例_使用Promise+XHR_獲取省份列表</title>
</head><body><p class="my-p"></p><script>/*** 目標:使用Promise管理XHR請求省份列表* 1. 創(chuàng)建Promise對象* 2. 執(zhí)行XHR異步代碼,獲取省份列表* 3. 關聯(lián)成功或失敗函數(shù),做后續(xù)處理*/const p = document.querySelector('.my-p')const promise = new Promise((resolve, reject) => {const xml = new XMLHttpRequest()xml.open('GET', 'http://hmajax.itheima.net/api/province')xml.addEventListener('loadend', function () {if (xml.status >= 200 && xml.status < 300) {// xml如何響應響應成功或者失敗?// 2xx開頭的響應狀態(tài)碼都是代表成功// console.log(xml.status)// console.log(xml.response)resolve(JSON.parse(xml.response))} else {reject(new Error(xml.response))// console.log(xml)}})xml.send()})promise.then(result => {console.log(result.list)p.innerHTML = result.list.join('<br>')})promise.catch(error => {// Error: <h1>404 Not Found</h1>// at XMLHttpRequest.<anonymous> (index.html:32:18)// 可以看出直接打印error錯誤信息不詳細// console.log(error) // 顯示詳細的錯誤信息,會返回一個對象,里面有message屬性console.dir(error)p.innerHTML = error.message})</script>
</body></html>
3.封裝簡易版 axios
3.1 封裝_簡易axios_獲取省份列表
- 1. 定義 myAxios 函數(shù),接收配置對象,返回 Promise 對象
- 2. 發(fā)起 XHR 請求,默認請求方法為 GET
- 3. 調用成功/失敗的處理程序
- 4. 使用 myAxios 函數(shù),獲取省份列表展示
代碼:
<body><p></p><script>/*** 目標:封裝_簡易axios函數(shù)_獲取省份列表* 1. 定義myAxios函數(shù),接收配置對象,返回Promise對象* 2. 發(fā)起XHR請求,默認請求方法為GET* 3. 調用成功/失敗的處理程序* 4. 使用myAxios函數(shù),獲取省份列表展示*/const p = document.querySelector('p')function myAxios(config) {// 返回一個promise對象return new Promise((resolve, reject) => {const xhr = new XMLHttpRequest()// 如果config.method沒有值,就默認GETxhr.open(config.method || 'GET', config.url)xhr.addEventListener('loadend', function () {// console.log(xhr.response)// 處理成功或者失敗的處理程序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'// method: 'GET'}).then(result => {console.log(result.list)p.innerHTML = result.list.join('<br>')}).catch(error => {console.log(error)p.innerHTML = error.message})</script>
</body>
3.2 封裝_簡易axios_獲取地區(qū)列表
- 1. myAxios 函數(shù)調用后,判斷 params 選項
- 2. 基于 URLSearchParams 轉換查詢參數(shù)字符串
- 3. 使用自己封裝的 myAxios 函數(shù)展示地區(qū)列表
代碼:
<body><p class="my-p"></p><script>/*** 目標:封裝_簡易axios函數(shù)_獲取地區(qū)列表* 1. 判斷有params選項,攜帶查詢參數(shù)* 2. 使用URLSearchParams轉換,并攜帶到url上* 3. 使用myAxios函數(shù),獲取地區(qū)列表*/function myAxios(config) {return new Promise((resolve, reject) => {const xhr = new XMLHttpRequest()if (config.params) {// 使用URLSearchParams轉換,并攜帶到url上const paramsObj = new URLSearchParams(config.params)const queryString = paramsObj.toString()// pname=%E8%BE%BD%E5%AE%81%E7%9C%81&cname=%E5%A4%A7%E8%BF%9E%E5%B8%82// console.log(queryString)// 拼接查詢字符串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))}})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>')})</script>
</body>
3.3?封裝_簡易axios_注冊用戶
- 1. myAxios 函數(shù)調用后,判斷 data 選項
- 2. 轉換數(shù)據(jù)類型,在 send 方法中發(fā)送
- 3. 使用自己封裝的 myAxios 函數(shù)完成注冊用戶功能
代碼:
<body><button class="reg-btn">注冊用戶</button><script>/*** 目標:封裝_簡易axios函數(shù)_注冊用戶* 1. 判斷有data選項,攜帶請求體* 2. 轉換數(shù)據(jù)類型,在send中發(fā)送* 3. 使用myAxios函數(shù),完成注冊用戶*/function myAxios(config) {return new Promise((resolve, reject) => {const xhr = new XMLHttpRequest()// 判斷是否有參數(shù)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))}})// 判斷是否有數(shù)據(jù)提交信息if (config.data) {// 告訴瀏覽器,傳輸?shù)臄?shù)據(jù)是JSON字符串xhr.setRequestHeader('Content-Type', 'application/json')// 處理數(shù)據(jù)提交const data = JSON.stringify(config.data)xhr.send(data)} else {xhr.send()}})}const btn = document.querySelector('.reg-btn')btn.addEventListener('click', function () {myAxios({url: 'http://hmajax.itheima.net/api/register',method: 'POST',data: {username: 'linhanxin1111',password: '1234567'}}).then(result => {console.log(result)})})</script>
</body>
3.4 簡單封裝完整版 axios
代碼:
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) {const jsonStr = JSON.stringify(config.data)xhr.setRequestHeader('Content-Type', 'application/json')xhr.send(jsonStr)} else {xhr.send()}})
}
4.案例 - 天氣預報
- 1. 獲取北京市天氣數(shù)據(jù),展示
- 2. 搜索城市列表,展示
- 3. 點擊城市,顯示對應天氣數(shù)據(jù)
接口文檔地址:https://apifox.com/apidoc/shared-1b0dd84f-faa8-435d-b355-5a8a329e34a8/api-87683404
效果圖:
4.1 天氣預報 - 獲取并渲染城市天氣

步驟:
- 1.默認顯示-北京市天氣
- 2.獲取北京市天氣數(shù)據(jù)
- 3.數(shù)據(jù)展示到頁面
代碼:
/*** 目標1:默認顯示-北京市天氣* 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ù)展示到頁面// 陽歷和農(nóng)歷日期const dateStr = `<span class="dateShort">${wObj.date}</span><span class="calendar">農(nóng)歷 <span class="dateLunar">${wObj.dateLunar}</span></span>`document.querySelector('.title').innerHTML = dateStr// 城市名字document.querySelector('.area').innerHTML = wObj.area// 當天氣溫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// 當天天氣const twObj = wObj.todayWeatherconst 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日天氣預報數(shù)據(jù)展示const dayForecast = wObj.dayForecastconst 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">${item.windPower}</span></div></li>`}).join('')// console.log(dayForecastStr)document.querySelector('.week-wrap').innerHTML = dayForecastStr})
}// 默認進入網(wǎng)頁-就要獲取天氣數(shù)據(jù)(北京市城市編碼:'110100')
getWeather('110100')
4.2?天氣預報 - 搜索城市列表
- 1. 綁定 input 事件,獲取關鍵字
- 2. 獲取展示城市列表數(shù)據(jù)
代碼:
/*** 目標2:搜索城市列表* 2.1 綁定input事件,獲取關鍵字* 2.2 獲取展示城市列表數(shù)據(jù)*/
// 2.1 綁定input事件,獲取關鍵字
document.querySelector('.search-city').addEventListener('input', (e) => {console.log(e.target.value)// 2.2 獲取展示城市列表數(shù)據(jù)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)document.querySelector('.search-list').innerHTML = liStr})
})
4.2 天氣預報 - 展示城市天氣
- 1. 檢測搜索列表點擊事件,獲取城市 code 值
- 2. 復用獲取展示城市天氣函數(shù)
代碼:
/*** 目標3:切換城市天氣* 3.1 綁定城市點擊事件,獲取城市code值* 3.2 調用獲取并展示天氣的函數(shù)*/
// 3.1 綁定城市點擊事件,獲取城市code值
document.querySelector('.search-list').addEventListener('click', e => {if (e.target.classList.contains('city-item')) {// 只有點擊城市l(wèi)i才會走這里const cityCode = e.target.dataset.codeconsole.log(cityCode)// 3.2 調用獲取并展示天氣的函數(shù)getWeather(cityCode)}
})