新聞中心
本人已經(jīng)過(guò)原 Danny Markov 授權(quán)翻譯

讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來(lái)自于我們對(duì)這個(gè)行業(yè)的熱愛。我們立志把好的技術(shù)通過(guò)有效、簡(jiǎn)單的方式提供給客戶,將通過(guò)不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:空間域名、網(wǎng)絡(luò)空間、營(yíng)銷軟件、網(wǎng)站建設(shè)、原州網(wǎng)站維護(hù)、網(wǎng)站推廣。
在本教程中,我們將學(xué)習(xí)如何使用 JS 進(jìn)行AJAX調(diào)用。
1.AJAX
術(shù)語(yǔ)AJAX 表示 異步的 JavaScript 和 XML。
AJAX 在 JS 中用于發(fā)出異步網(wǎng)絡(luò)請(qǐng)求來(lái)獲取資源。當(dāng)然,不像名稱所暗示的那樣,資源并不局限于XML,還用于獲取JSON、HTML或純文本等資源。
有多種方法可以發(fā)出網(wǎng)絡(luò)請(qǐng)求并從服務(wù)器獲取數(shù)據(jù)。我們將一一介紹。
2.XMLHttpRequest
XMLHttpRequest對(duì)象(簡(jiǎn)稱XHR)在較早的時(shí)候用于從服務(wù)器異步檢索數(shù)據(jù)。
之所以使用XML,是因?yàn)樗紫扔糜跈z索XML數(shù)據(jù)?,F(xiàn)在,它也可以用來(lái)檢索JSON, HTML或純文本。
事例 2.1: GET
- function success() {
- var data = JSON.parse(this.responseText)
- console.log(data)
- }
- function error (err) {
- console.log('Error Occurred:', err)
- }
- var xhr = new XMLHttpRequest()
- xhr.onload = success
- xhr.onerror = error
- xhr.open("GET", ""https://jsonplaceholder.typicode.com/posts/1")
- xhr.send()
我們看到,要發(fā)出一個(gè)簡(jiǎn)單的GET請(qǐng)求,需要兩個(gè)偵聽器來(lái)處理請(qǐng)求的成功和失敗。我們還需要調(diào)用open()和send()方法。來(lái)自服務(wù)器的響應(yīng)存儲(chǔ)在responseText變量中,該變量使用JSON.parse()轉(zhuǎn)換為JavaScript 對(duì)象。
- function success() {
- var data = JSON.parse(this.responseText);
- console.log(data);
- }
- function error(err) {
- console.log('Error Occurred :', err);
- }
- var xhr = new XMLHttpRequest();
- xhr.onload = success;
- xhr.onerror = error;
- xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");
- xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
- xhr.send(JSON.stringify({
- title: 'foo',
- body: 'bar',
- userId: 1
- })
- );
我們看到POST請(qǐng)求類似于GET請(qǐng)求。我們需要另外使用setRequestHeader設(shè)置請(qǐng)求標(biāo)頭“Content-Type” ,并使用send方法中的JSON.stringify將JSON正文作為字符串發(fā)送。
2.3 XMLHttpRequest vs Fetch
早期的開發(fā)人員,已經(jīng)使用了好多年的 XMLHttpRequest來(lái)請(qǐng)求數(shù)據(jù)了?,F(xiàn)代的fetch API允許我們發(fā)出類似于XMLHttpRequest(XHR)的網(wǎng)絡(luò)請(qǐng)求。主要區(qū)別在于fetch()API使用Promises,它使 API更簡(jiǎn)單,更簡(jiǎn)潔,避免了回調(diào)地獄。
3. Fetch API
Fetch 是一個(gè)用于進(jìn)行AJAX調(diào)用的原生 JavaScript API,它得到了大多數(shù)瀏覽器的支持,現(xiàn)在得到了廣泛的應(yīng)用。
3.1 API用法
- fetch(url, options)
- .then(response => {
- // handle response data
- })
- .catch(err => {
- // handle errors
- });
API參數(shù)
fetch() API有兩個(gè)參數(shù)
1.url是必填參數(shù),它是您要獲取的資源的路徑。
2.options是一個(gè)可選參數(shù)。不需要提供這個(gè)參數(shù)來(lái)發(fā)出簡(jiǎn)單的GET請(qǐng)求。
- method: GET | POST | PUT | DELETE | PATCH
- headers: 請(qǐng)求頭,如 { “Content-type”: “application/json; charset=UTF-8” }
- mode: cors | no-cors | same-origin | navigate
- cache: default | reload | no-cache
- body: 一般用于POST請(qǐng)求
API返回Promise對(duì)象
fetch() API返回一個(gè)promise對(duì)象。
- 如果存在網(wǎng)絡(luò)錯(cuò)誤,則將拒絕,這會(huì)在.catch()塊中處理。
- 如果來(lái)自服務(wù)器的響應(yīng)帶有任何狀態(tài)碼(如200、404、500),則promise將被解析。響應(yīng)對(duì)象可以在.then()塊中處理。
錯(cuò)誤處理
請(qǐng)注意,對(duì)于成功的響應(yīng),我們期望狀態(tài)代碼為200(正常狀態(tài)),但是即使響應(yīng)帶有錯(cuò)誤狀態(tài)代碼(例如404(未找到資源)和500(內(nèi)部服務(wù)器錯(cuò)誤)),fetch() API 的狀態(tài)也是 resolved,我們需要在.then() 塊中顯式地處理那些。
我們可以在response 對(duì)象中看到HTTP狀態(tài):
- HTTP狀態(tài)碼,例如200。
- ok –布爾值,如果HTTP狀態(tài)代碼為200-299,則為true。
3.3 示例:GET
- const getTodoItem = fetch('https://jsonplaceholder.typicode.com/todos/1')
- .then(response => response.json())
- .catch(err => console.error(err));
- getTodoItem.then(response => console.log(response));
- Response
- { userId: 1, id: 1, title: "delectus aut autem", completed: false }
在上面的代碼中需要注意兩件事:
- fetch API返回一個(gè)promise對(duì)象,我們可以將其分配給變量并稍后執(zhí)行。
- 我們還必須調(diào)用response.json()將響應(yīng)對(duì)象轉(zhuǎn)換為JSON
錯(cuò)誤處理
我們來(lái)看看當(dāng)HTTP GET請(qǐng)求拋出500錯(cuò)誤時(shí)會(huì)發(fā)生什么:
- fetch('http://httpstat.us/500') // this API throw 500 error
- .then(response => () => {
- console.log("Inside first then block");
- return response.json();
- })
- .then(json => console.log("Inside second then block", json))
- .catch(err => console.error("Inside catch block:", err));
- Inside first then block
- ? Inside catch block: SyntaxError: Unexpected token I in JSON at position 4
我們看到,即使API拋出500錯(cuò)誤,它仍然會(huì)首先進(jìn)入then()塊,在該塊中它無(wú)法解析錯(cuò)誤JSON并拋出catch()塊捕獲的錯(cuò)誤。
這意味著如果我們使用fetch()API,則需要像這樣顯式地處理此類錯(cuò)誤:-
- fetch('http://httpstat.us/500')
- .then(handleErrors)
- .then(response => response.json())
- .then(response => console.log(response))
- .catch(err => console.error("Inside catch block:", err));
- function handleErrors(response) {
- if (!response.ok) { // throw error based on custom conditions on response
- throw Error(response.statusText);
- }
- return response;
- }
- Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)
3.3 示例:POST
- fetch('https://jsonplaceholder.typicode.com/todos', {
- method: 'POST',
- body: JSON.stringify({
- completed: true,
- title: 'new todo item',
- userId: 1
- }),
- headers: {
- "Content-type": "application/json; charset=UTF-8"
- }
- })
- .then(response => response.json())
- .then(json => console.log(json))
- .catch(err => console.log(err))
- Response
- {completed: true, title: "new todo item", userId: 1, id: 201}
在上面的代碼中需要注意兩件事:-
- POST請(qǐng)求類似于GET請(qǐng)求。我們還需要在fetch() API的第二個(gè)參數(shù)中發(fā)送method,body 和headers 屬性。
- 我們必須需要使用 JSON.stringify() 將對(duì)象轉(zhuǎn)成字符串請(qǐng)求body 參數(shù)
4.Axios API
Axios API非常類似于fetch API,只是做了一些改進(jìn)。我個(gè)人更喜歡使用Axios API而不是fetch() API,原因如下:
- 為GET 請(qǐng)求提供 axios.get(),為 POST 請(qǐng)求提供 axios.post()等提供不同的方法,這樣使我們的代碼更簡(jiǎn)潔。
- 將響應(yīng)代碼(例如404、500)視為可以在catch()塊中處理的錯(cuò)誤,因此我們無(wú)需顯式處理這些錯(cuò)誤。
- 它提供了與IE11等舊瀏覽器的向后兼容性
- 它將響應(yīng)作為JSON對(duì)象返回,因此我們無(wú)需進(jìn)行任何解析
4.1 示例:GET
- // 在chrome控制臺(tái)中引入腳本的方法
- var script = document.createElement('script');
- script.type = 'text/javascript';
- script.src = 'https://unpkg.com/axios/dist/axios.min.js';
- document.head.appendChild(script);
- axios.get('https://jsonplaceholder.typicode.com/todos/1')
- .then(response => console.log(response.data))
- .catch(err => console.error(err));
- Response
- { userId: 1, id: 1, title: "delectus aut autem", completed: false }
我們可以看到,我們直接使用response獲得響應(yīng)數(shù)據(jù)。數(shù)據(jù)沒有任何解析對(duì)象,不像fetch() API。
錯(cuò)誤處理
- axios.get('http://httpstat.us/500')
- .then(response => console.log(response.data))
- .catch(err => console.error("Inside catch block:", err));
- Inside catch block: Error: Network Error
我們看到,500錯(cuò)誤也被catch()塊捕獲,不像fetch() API,我們必須顯式處理它們。
4.2 示例:POST
- axios.post('https://jsonplaceholder.typicode.com/todos', {
- completed: true,
- title: 'new todo item',
- userId: 1
- })
- .then(response => console.log(response.data))
- .catch(err => console.log(err))
- {completed: true, title: "new todo item", userId: 1, id: 201}
我們看到POST方法非常簡(jiǎn)短,可以直接傳遞請(qǐng)求主體參數(shù),這與fetch()API不同。
作者:Danny Markov 譯者:前端小智 來(lái)源:tutorialzine
原文:https://tutorialzine.com/2017/12-terminal-commands-every-web-developer-should-know
本文轉(zhuǎn)載自微信公眾號(hào)「大遷世界」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系大遷世界公眾號(hào)。
分享標(biāo)題:在JS中如何使用Ajax來(lái)進(jìn)行請(qǐng)求
網(wǎng)站URL:http://m.fisionsoft.com.cn/article/dhdisij.html


咨詢
建站咨詢
