Ajax 與 Axios 異步請求
一、服務(wù)器對外提供了哪些資源
1. 網(wǎng)頁中如何請求數(shù)據(jù)
數(shù)據(jù),也是服務(wù)器對外提供的一種資源。只要是資源,必然要通過 請求 – 處理 – 響應(yīng) 的方式進行獲取。如果要在網(wǎng)頁中請求服務(wù)器上的數(shù)據(jù)資源,則需要用到 XMLHttpRequest 對象。XMLHttpRequest(簡稱 xhr)是瀏覽器提供的 js 成員,通過它,可以請求服務(wù)器上的數(shù)據(jù)資源。最簡單的用法 var xhrObj = new XMLHttpRequest()
2. 資源的請求方式
客戶端請求服務(wù)器時,請求的方式有很多種,最常見的兩種請求方式分別為 get 和 post 請求。
-
get 請求通常用于獲取服務(wù)端資源(向服務(wù)器要資源)
例如:根據(jù) URL 地址,從服務(wù)器獲取 HTML 文件、css 文件、js文件、圖片文件、數(shù)據(jù)資源等
-
post 請求通常用于向服務(wù)器提交數(shù)據(jù)(往服務(wù)器發(fā)送資源)
例如:登錄時向服務(wù)器提交的登錄信息、注冊時向服務(wù)器提交的注冊信息、添加用戶時向服務(wù)器提交的用戶信息等各種數(shù)據(jù)提交操作
二、Ajax 異步請求
1. 什么是Ajax
Ajax 的全稱是 Asynchronous Javascript And XML(異步 JavaScript 和 XML)。通俗的理解:在網(wǎng)頁中利用 XMLHttpRequest 對象和服務(wù)器進行數(shù)據(jù)交互的方式,就是Ajax。
瀏覽器中提供的 XMLHttpRequest 用法比較復(fù)雜,所以 jQuery 對 XMLHttpRequest 進行了封裝,提供了一系列 Ajax 相關(guān)的函數(shù),極大地降低了 Ajax 的使用難度
2. 為什么要學(xué)Ajax
之前所學(xué)的技術(shù),只能把網(wǎng)頁做的更美觀漂亮,或添加一些動畫效果,但是,Ajax能讓我們輕松實現(xiàn)網(wǎng)頁與服務(wù)器之間的數(shù)據(jù)交互。
3. Ajax的典型應(yīng)用場景
- 用戶名檢測:注冊用戶時,通過
ajax
的形式,動態(tài)檢測用戶名是否被占用 - 搜索提示:當(dāng)輸入搜索關(guān)鍵字時,通過
ajax
的形式,動態(tài)加載搜索提示列表 - 數(shù)據(jù)分頁顯示:當(dāng)點擊頁碼值的時候,通過
ajax
的形式,根據(jù)頁碼值動態(tài)刷新表格的數(shù)據(jù) - 數(shù)據(jù)的增刪改查:數(shù)據(jù)的添加、刪除、修改、查詢操作,都需要通過
ajax
的形式,來實現(xiàn)數(shù)據(jù)的交互
4. Ajax 的應(yīng)用
-
jQuery 中發(fā)起 Ajax 請求最常用的三個方法
// get請求 $.get() // post請求 $.post() // 通用請求 $.ajax()
-
$.get()函數(shù)的語法
jQuery 中 $.get() 函數(shù)的功能單一,專門用來發(fā)起 get 請求,從而將服務(wù)器上的資源請求到客戶端來進行使用。$.get() 函數(shù)的語法如下:
-
$.get() 函數(shù)的語法如下:
$.get(url, [data], [callback])
-
其中,三個參數(shù)各自代表的含義如下:
參數(shù)名 參數(shù)類型 是否必選 說明 url
string 是 要請求的資源地址 data object 否 請求資源期間要攜帶的參數(shù) callback function 否 請求成功時的回調(diào)函數(shù) -
$.get()發(fā)起不帶參數(shù)的請求
// 使用 $.get() 函數(shù)發(fā)起不帶參數(shù)的請求時,直接提供請求的 URL 地址和請求成功之后的回調(diào)函數(shù)即可: $.get("http://ajax-base-api-t.itheima.net/api/getbooks",?function(res)?{ console.log(res) // 這里的 res 是服務(wù)器返回的數(shù)據(jù) })
-
$.get()發(fā)起帶參數(shù)的請求
// 使用 $.get() 函數(shù)發(fā)起帶參數(shù)的請求時,示例代碼如下: $.get("http://ajax-base-api-t.itheima.net/api/getbooks",?{ id: 1 }, function(res)?{ console.log(res) })
-
-
$.post()函數(shù)的語法
jQuery 中 $.post() 函數(shù)的功能單一,專門用來發(fā)起 post 請求,從而向服務(wù)器提交數(shù)據(jù)。
-
$.post() 函數(shù)的語法如下:
$.post(url, [data], [callback])
-
其中,三個參數(shù)各自代表的含義如下:
參數(shù)名 參數(shù)類型 是否必選 說明 url
string 是 提交數(shù)據(jù)的地址 data object 否 要提交的數(shù)據(jù) callback function 否 數(shù)據(jù)提交成功時的回調(diào)函數(shù) -
$.post()向服務(wù)器提交數(shù)據(jù)
// 使用 $post() 向服務(wù)器提交數(shù)據(jù)的示例代碼如下: $.post( "http://ajax-base-api-t.itheima.net/api/addbook", // 請求的URL地址 { bookname: '水滸傳', author: '施耐庵', publisher: '上海圖書出版社' }, // 提交的數(shù)據(jù) function(res) { // 回調(diào)函數(shù) console.log(res) } )
-
-
$.ajax()
函數(shù)的語法相比于 $.get() 和 $.post() 函數(shù),jQuery 中提供的 $.ajax() 函數(shù),是一個功能比較綜合的函數(shù),它允許我們對 Ajax 請求進行更詳細(xì)的配置。
-
$.ajax()
函數(shù)的基本語法如下:$.ajax({ type: '', // 請求的方式,例如 GET 或 POST url: '', // 請求的 URL 地址 data: { },// 這次請求要攜帶的數(shù)據(jù) success: function(res) { } // 請求成功之后的回調(diào)函數(shù) })
-
使用
$.ajax()
發(fā)起GET請求// 使用 $.ajax() 發(fā)起 GET 請求時,只需要將 type 屬性的值設(shè)置為 'GET' 即可: $.ajax({ type: 'GET', // 請求的方式 url: "http://ajax-base-api-t.itheima.net/api/getbooks", // 請求的 URL 地址 data: { id: 1 },// 這次請求要攜帶的數(shù)據(jù) success: function(res) { // 請求成功之后的回調(diào)函數(shù) console.log(res) } })
-
GET請求實戰(zhàn)案例前后端交互
-
前端代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>加法運算</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> </head> <body> <div> <h3>ajax GET請求頁面</h3> <input type="text"> + <input type="text"> = <input type="text"> <input type="button" value="計算"> </div> <script> let nums = $("input[type='text']"); let btn = $("input[type='button']"); btn.click(function (){ // 發(fā)起get請求: http://127.0.0.1:8888/calc?num1=1.3&num2=3.6 $.ajax({ url:"/calc", type:"get", dataType:"json", data:{ "num1": Number(nums.eq(0).val()), "num2": Number(nums.eq(1).val()) }, success:function (response) { console.log("響應(yīng)數(shù)據(jù):",response); console.log("響應(yīng)數(shù)據(jù)類型:",typeof(response)); nums.eq(2).val(response["result"]); }, error:function (error) { console.log(error.readyState); console.log(error.status); console.log(error.statusText); console.log(error.responseText); } }) }) </script> </body> </html>
-
后端代碼
import tornado.web import tornado.ioloop class MainHandler(tornado.web.RequestHandler): def get(self): self.render("calc_get.html") class ReferHandler(tornado.web.RequestHandler): def get(self): # print("請求頭信息\n:", self.request.headers) print("請求url: ", self.request.full_url()) # 獲取原始查詢參數(shù)和請求體參數(shù) print("查詢參數(shù):", self.request.arguments) print("請求體參數(shù):", self.request.body) # 框架解析之后的數(shù)據(jù), 如果原始查詢參數(shù)無數(shù)據(jù)則報錯 num1 = self.get_argument("num1") num2 = self.get_argument("num2") # 通過url以鍵值對形式傳參解析出來的數(shù)據(jù)均為字符串格式 print("接收的查詢參數(shù)num1類型為", type(num1)) print("接收的查詢參數(shù)num1, num2值為", num1, num2) result = round(float(num1) + float(num2), 4) # .write會檢測參數(shù),將字典轉(zhuǎn)為json數(shù)據(jù)以后返回 self.write({"result": result}) if __name__ == '__main__': app = tornado.web.Application([ ("/", MainHandler), ("/calc", ReferHandler), ]) app.listen(8888) tornado.ioloop.IOLoop.current().start()
-
-
-
使用
$.ajax()
發(fā)起POST請求// 使用 $.ajax() 發(fā)起 POST 請求時,只需要將 type 屬性的值設(shè)置為 'POST' 即可: $.ajax({ type: 'POST', // 請求的方式 url: "http://ajax-base-api-t.itheima.net/api/addbook", // 請求的 URL 地址 data: { // 要提交給服務(wù)器的數(shù)據(jù) bookname:?'水滸傳', author:?'施耐庵', publisher:?'上海圖書出版社' }, success: function(res) { // 請求成功之后的回調(diào)函數(shù) console.log(res) } })
-
POST請求實戰(zhàn)案例前后端交互
-
前端代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>加法運算</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> </head> <body> <div> <h3>ajax POST請求頁面</h3> <input type="text"> + <input type="text"> = <input type="text"> <input type="button" value="計算"> </div> <script> let nums = $("input[type='text']"); let btn = $("input[type='button']"); btn.click(function (){ // 發(fā)起post請求: http://127.0.0.1:8888 $.ajax({ url:"/", type:"post", // post請求一般會指定發(fā)送給服務(wù)器的數(shù)據(jù)格式 contentType:"application/json", dataType:"json", // 將數(shù)據(jù)轉(zhuǎn)換為json格式發(fā)送 data:JSON.stringify({ "num1": Number(nums.eq(0).val()), "num2": Number(nums.eq(1).val()) }), success:function (response) { console.log("響應(yīng)數(shù)據(jù):",response); console.log("響應(yīng)數(shù)據(jù)類型:",typeof(response)); nums.eq(2).val(response["result"]); }, error:function (error) { console.log(error.readyState); console.log(error.status); console.log(error.statusText); console.log(error.responseText); } }) }) </script> </body> </html>
-
后端代碼
import json import tornado.web import tornado.ioloop class MainHandler(tornado.web.RequestHandler): def get(self): self.render("calc_post.html") def post(self): # print("請求頭信息\n:", self.request.headers) print("請求url: ", self.request.full_url()) # 獲取原始查詢參數(shù)和請求體參數(shù) print("查詢參數(shù):", self.request.arguments) print("請求體參數(shù):", self.request.body) # 框架解析之后的數(shù)據(jù) data = json.loads(self.request.body) num1 = data["num1"] num2 = data["num2"] print("接收的請求體參數(shù)num1類型為", type(num1)) print("接收的請求體參數(shù)num1, num2值為", num1, num2) result = round(num1 + num2, 4) # .write會檢測參數(shù),將字典轉(zhuǎn)為json數(shù)據(jù)以后返回 self.write({"result": result}) if __name__ == '__main__': app = tornado.web.Application([ ("/", MainHandler), ]) app.listen(8888) tornado.ioloop.IOLoop.current().start()
-
-
-
ajax
異步請求參數(shù)說明【contentType】: 發(fā)送給服務(wù)器的數(shù)據(jù)格式; 可選4種格式: 1> application/x-www-form-urlencoded: 默認(rèn)方式,在請求發(fā)送過程中會對數(shù)據(jù)進行序列化處理,以鍵值對形式 ?key1=value1&key2=value的方式發(fā)送到服務(wù)器 2> multipart/form-data: 需要在表單中進行文件上傳時,就需要使用該格式 3> application/json: 消息主體是序列化后的 JSON 字符串 4> text/plain: 數(shù)據(jù)以純文本形式(text/json/xml/html)進行編碼,其中不含任何控件或格式字符 eg: contentType:"application/json", 【dataType】: 用什么格式解析服務(wù)端響應(yīng)的數(shù)據(jù)(并非是原生ajax的屬性),有些框架(比如jquery)默認(rèn)(未填寫dataType或解析錯誤的情況下)讀取服務(wù)端的響應(yīng)頭Content-Type 1> text:默認(rèn)值。預(yù)期數(shù)據(jù)為純文本字符串。 2> html:預(yù)期數(shù)據(jù)為html格式的字符串。 3> json:預(yù)期數(shù)據(jù)為JSON格式的對象或數(shù)組。 4> xml:預(yù)期數(shù)據(jù)為XML文檔類型的數(shù)據(jù)。 說明: 指定dataType參數(shù)后,如果返回的數(shù)據(jù)類型與預(yù)期不符合,則ajax請求會失敗,并觸發(fā)error回調(diào)函數(shù)。因此,正確指定dataType參數(shù)對于確保ajax請求的數(shù)據(jù)類型是非常重要的。 【jquery ajax 出錯信息解讀-error屬性值】 1> readyState :當(dāng)前狀態(tài),0-未初始化,1-正在載入,2-已經(jīng)載入,3-數(shù)據(jù)進行交互,4-完成。 2> status :返回的HTTP狀態(tài)碼,比如常見的404,500等錯誤代碼。 3> statusText :對應(yīng)狀態(tài)碼的錯誤信息,比如404錯誤信息是not found,500是Internal Server Error。 4> responseText :服務(wù)器響應(yīng)返回的文本信息
-
三、 Axios 異步請求
1. 什么是axios
Axios 是基于Promise的HTTP客戶端作用于瀏覽器和node.js,專注于網(wǎng)絡(luò)數(shù)據(jù)請求的庫。相比于原生的 XMLHttpRequest 對象,axios 簡單易用。相比于 jQuery,axios 更加輕量化,只專注于網(wǎng)絡(luò)數(shù)據(jù)請求。
2. axios 的應(yīng)用
-
axios
發(fā)起GET請求-
axios
發(fā)起 get 請求的語法:axios.get('url', { params: { /*參數(shù)*/ } }).then(callback)
-
具體的請求示例如下:
//?請求的?URL?地址 var?url?=?'http://ajax-base-api-t.itheima.net/api/get' //?請求的參數(shù)對象 var?paramsObj?=?{?name:?'zs',?age:?20?} //?調(diào)用?axios.get()?發(fā)起?GET?請求 axios.get(url,?{?params:?paramsObj?}).then(function(res)?{ //?res.data?是服務(wù)器返回的數(shù)據(jù) var?result?=?res.data console.log(res) })
-
-
axios
發(fā)起POST請求-
axios
發(fā)起 post 請求的語法:axios.post('url', { /*參數(shù)*/ }).then(callback)
-
具體的請求示例如下:
//?請求的?URL?地址 var?url?=?'http://ajax-base-api-t.itheima.net/api/post' //?要提交到服務(wù)器的數(shù)據(jù) var?dataObj?=?{?location:?'北京',?address:?'順義'?} //?調(diào)用?axios.post()?發(fā)起?POST?請求 axios.post(url,?dataObj).then(function(res)?{ //?res.data?是服務(wù)器返回的數(shù)據(jù) var?result?=?res.data console.log(result) })
-
-
直接使用
axios
發(fā)起請求-
直接使用
axios
發(fā)起請求,axios
也提供了類似于jQuery
中$.ajax()
的函數(shù),語法如下:axios({ method:?'請求類型', url:?'請求的URL地址', data:?{?/*?POST數(shù)據(jù)?*/?}, params:?{?/*?GET參數(shù)?*/?} }) .then(callback)
-
直接使用
axios
發(fā)起GET請求axios({ method:?'GET', url:?'http://www.liulongbin.top:3006/api/get', params:?{ // GET 參數(shù)要通過 params 屬性提供 name:?'zs', ?????????age:?20 ?????} }).then(function(res)?{ console.log(res.data) })
-
直接使用
axios
發(fā)起POST請求axios({ method:?'POST', url:?'http://www.liulongbin.top:3006/api/post', data:?{ // POST 數(shù)據(jù)要通過 data 屬性提供 bookname:?'程序員的自我修養(yǎng)', ?????????price:?666 ?????} }).then(function(res)?{ console.log(res.data) })
-
四、 接口
-
接口的概念
使用 Ajax 請求數(shù)據(jù)時,被請求的 URL 地址,就叫做數(shù)據(jù)接口(簡稱接口)。同時,每個接口必須有請求方式。 例如: http://ajax-base-api-t.itheima.net/api/getbooks 獲取圖書列表的接口(GET請求) http://ajax-base-api-t.itheima.net/api/addbook 添加圖書的接口(POST請求)
-
接口的請求過程
-
接口文檔
-
什么是接口文檔
接口文檔,顧名思義就是接口的說明文檔,它是我們調(diào)用接口的依據(jù)。好的接口文檔包含了對接口URL,參數(shù)以及輸出內(nèi)容的說明,我們參照接口文檔就能方便的知道接口的作用,以及接口如何進行調(diào)用。
-
接口文檔的組成部分
接口文檔可以包含很多信息,也可以按需進行精簡,不過,一個合格的接口文檔,應(yīng)該包含以下6項內(nèi)容,從而為接口的調(diào)用提供依據(jù):
- 接口名稱:用來標(biāo)識各個接口的簡單說明,如登錄接口,獲取圖書列表接口等。
- 接口URL:接口的調(diào)用地址
- 調(diào)用方式:接口的調(diào)用方式,如 GET 或 POST
- 參數(shù)格式:接口需要傳遞的參數(shù),每個參數(shù)必須包含參數(shù)名稱、參數(shù)類型、是否必選、參數(shù)說明這4項內(nèi)容
- 響應(yīng)格式:接口的返回值的詳細(xì)描述,一般包含數(shù)據(jù)名稱、數(shù)據(jù)類型、說明3項內(nèi)容。
- 返回示例(可選):通過對象的形式,例舉服務(wù)器返回數(shù)據(jù)的結(jié)構(gòu)。
-
接口文檔示例
-
圖書列表
-
接口URL:
/api/getbooks
-
調(diào)用方式: GET
-
參數(shù)格式 -
PTND
:參數(shù)名稱( params
)參數(shù)類型(type) 是否必選(necessary) 參數(shù)說明(description) id
Number 否 圖書Id bookname
String 否 圖書名稱 author
String 否 作者 publisher
String 否 出版社 -
響應(yīng)格式 -
PTD
:文章來源:http://www.zghlxwxcb.cn/news/detail-844107.html數(shù)據(jù)名稱 數(shù)據(jù)類型 說明 status
Number 200 成功;500 失??; msg
String 對 status 字段的詳細(xì)說明 data
Array 圖書列表 +id
Number 圖書Id +bookname
String 圖書名稱 +author
String 作者 +publisher
String 出版社 -
返回示例:文章來源地址http://www.zghlxwxcb.cn/news/detail-844107.html
{ "status": 200, "msg": "獲取圖書列表成功", "data": [ { "id": 1, "bookname": "西游記", "author": "吳承恩", "publisher": "北京圖書出版社" }, { "id": 2, "bookname": "紅樓夢", "author": "曹雪芹", "publisher": "上海圖書出版社" }, { "id": 3, "bookname": "三國演義", "author": "羅貫中", "publisher": "北京圖書出版社" } ] }
-
-
-
到了這里,關(guān)于Ajax 與 Axios 異步請求的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!