本人已經(jīng)過原 Danny Markov 授權(quán)翻譯
在本教程中,我們將學(xué)習(xí)如何使用 JS 進行AJAX調(diào)用。
1.AJAX
術(shù)語AJAX 表示 異步的 JAVAScript 和 XML。
AJAX 在 JS 中用于發(fā)出異步網(wǎng)絡(luò)請求來獲取資源。當(dāng)然,不像名稱所暗示的那樣,資源并不局限于XML,還用于獲取JSON、html或純文本等資源。
有多種方法可以發(fā)出網(wǎng)絡(luò)請求并從服務(wù)器獲取數(shù)據(jù)。我們將一一介紹。
2.XMLHttpRequest
XMLHttpRequest對象(簡稱XHR)在較早的時候用于從服務(wù)器異步檢索數(shù)據(jù)。
之所以使用XML,是因為它首先用于檢索XML數(shù)據(jù)。現(xiàn)在,它也可以用來檢索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ā)出一個簡單的GET請求,需要兩個偵聽器來處理請求的成功和失敗。我們還需要調(diào)用open()和send()方法。來自服務(wù)器的響應(yīng)存儲在responseText變量中,該變量使用JSON.parse()轉(zhuǎn)換為JavaScript 對象。
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請求類似于GET請求。我們需要另外使用setRequestHeader設(shè)置請求標(biāo)頭“Content-Type” ,并使用send方法中的JSON.stringify將JSON正文作為字符串發(fā)送。
2.3 XMLHttpRequest vs Fetch
早期的開發(fā)人員,已經(jīng)使用了好多年的 XMLHttpRequest來請求數(shù)據(jù)了。現(xiàn)代的fetch API允許我們發(fā)出類似于XMLHttpRequest(XHR)的網(wǎng)絡(luò)請求。主要區(qū)別在于fetch()API使用Promises,它使 API更簡單,更簡潔,避免了回調(diào)地獄。
3. Fetch API
Fetch 是一個用于進行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有兩個參數(shù)
- url是必填參數(shù),它是您要獲取的資源的路徑。
- options是一個可選參數(shù)。不需要提供這個參數(shù)來發(fā)出簡單的GET請求。
- method: GET | POST | PUT | DELETE | PATCH
- headers: 請求頭,如 { “Content-type”: “application/json; charset=UTF-8” }
- mode: cors | no-cors | same-origin | navigate
- cache: default | reload | no-cache
- body: 一般用于POST請求
API返回Promise對象
fetch() API返回一個promise對象。
- 如果存在網(wǎng)絡(luò)錯誤,則將拒絕,這會在.catch()塊中處理。
- 如果來自服務(wù)器的響應(yīng)帶有任何狀態(tài)碼(如200、404、500),則promise將被解析。響應(yīng)對象可以在.then()塊中處理。
錯誤處理
請注意,對于成功的響應(yīng),我們期望狀態(tài)代碼為200(正常狀態(tài)),但是即使響應(yīng)帶有錯誤狀態(tài)代碼(例如404(未找到資源)和500(內(nèi)部服務(wù)器錯誤)),fetch() API 的狀態(tài)也是 resolved,我們需要在.then() 塊中顯式地處理那些。
我們可以在response 對象中看到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返回一個promise對象,我們可以將其分配給變量并稍后執(zhí)行。
- 我們還必須調(diào)用response.json()將響應(yīng)對象轉(zhuǎn)換為JSON
錯誤處理
我們來看看當(dāng)HTTP GET請求拋出500錯誤時會發(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錯誤,它仍然會首先進入then()塊,在該塊中它無法解析錯誤JSON并拋出catch()塊捕獲的錯誤。
這意味著如果我們使用fetch()API,則需要像這樣顯式地處理此類錯誤:-
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請求類似于GET請求。我們還需要在fetch() API的第二個參數(shù)中發(fā)送method,body 和headers 屬性。
- 我們必須需要使用 JSON.stringify() 將對象轉(zhuǎn)成字符串請求body參數(shù)
4.AxIOS API
Axios API非常類似于fetch API,只是做了一些改進。我個人更喜歡使用Axios API而不是fetch() API,原因如下:
- 為GET 請求提供 axios.get(),為 POST 請求提供 axios.post()等提供不同的方法,這樣使我們的代碼更簡潔。
- 將響應(yīng)代碼(例如404、500)視為可以在catch()塊中處理的錯誤,因此我們無需顯式處理這些錯誤。
- 它提供了與IE11等舊瀏覽器的向后兼容性
- 它將響應(yīng)作為JSON對象返回,因此我們無需進行任何解析
4.1 示例:GET
// 在chrome控制臺中引入腳本的方法
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ù)沒有任何解析對象,不像fetch() API。
錯誤處理
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錯誤也被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方法非常簡短,可以直接傳遞請求主體參數(shù),這與fetch()API不同。
作者:Danny Markov 譯者:前端小智 來源:tutorialzine
原文:https://tutorialzine.com/2017/12-terminal-commands-every-web-developer-should-know