在 JS 中如何使用 Ajax 來進行請求
本人已經過原 Danny Markov 授權翻譯
在本教程中,我們將學習如何使用 JS 進行AJAX調用。
1.AJAX
術語AJAX 表示 異步的 JavaScript 和 XML。
AJAX 在 JS 中用于發出異步網絡請求來獲取資源。當然,不像名稱所暗示的那樣,資源并不局限于XML,還用于獲取JSON、HTML或純文本等資源。
有多種方法可以發出網絡請求并從服務器獲取數據。我們將一一介紹。
2.XMLHttpRequest
XMLHttpRequest對象(簡稱XHR)在較早的時候用于從服務器異步檢索數據。
之所以使用XML,是因為它首先用于檢索XML數據。現在,它也可以用來檢索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()
我們看到,要發出一個簡單的GET請求,需要兩個偵聽器來處理請求的成功和失敗。我們還需要調用open()和send()方法。來自服務器的響應存儲在responseText變量中,該變量使用JSON.parse()轉換為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設置請求標頭“Content-Type” ,并使用send方法中的JSON.stringify將JSON正文作為字符串發送。
2.3 XMLHttpRequest vs Fetch
早期的開發人員,已經使用了好多年的 XMLHttpRequest來請求數據了。現代的fetch API允許我們發出類似于XMLHttpRequest(XHR)的網絡請求。主要區別在于fetch()API使用Promises,它使 API更簡單,更簡潔,避免了回調地獄。
3. Fetch API
Fetch 是一個用于進行AJAX調用的原生 JavaScript API,它得到了大多數瀏覽器的支持,現在得到了廣泛的應用。
3.1 API用法
- fetch(url, options)
- .then(response => {
- // handle response data
- })
- .catch(err => {
- // handle errors
- });
API參數
fetch() API有兩個參數
1.url是必填參數,它是您要獲取的資源的路徑。
2.options是一個可選參數。不需要提供這個參數來發出簡單的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對象。
- 如果存在網絡錯誤,則將拒絕,這會在.catch()塊中處理。
- 如果來自服務器的響應帶有任何狀態碼(如200、404、500),則promise將被解析。響應對象可以在.then()塊中處理。
錯誤處理
請注意,對于成功的響應,我們期望狀態代碼為200(正常狀態),但是即使響應帶有錯誤狀態代碼(例如404(未找到資源)和500(內部服務器錯誤)),fetch() API 的狀態也是 resolved,我們需要在.then() 塊中顯式地處理那些。
我們可以在response 對象中看到HTTP狀態:
- HTTP狀態碼,例如200。
- ok –布爾值,如果HTTP狀態代碼為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對象,我們可以將其分配給變量并稍后執行。
- 我們還必須調用response.json()將響應對象轉換為JSON
錯誤處理
我們來看看當HTTP GET請求拋出500錯誤時會發生什么:
- 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的第二個參數中發送method,body 和headers 屬性。
- 我們必須需要使用 JSON.stringify() 將對象轉成字符串請求body 參數
4.Axios API
Axios API非常類似于fetch API,只是做了一些改進。我個人更喜歡使用Axios API而不是fetch() API,原因如下:
- 為GET 請求提供 axios.get(),為 POST 請求提供 axios.post()等提供不同的方法,這樣使我們的代碼更簡潔。
- 將響應代碼(例如404、500)視為可以在catch()塊中處理的錯誤,因此我們無需顯式處理這些錯誤。
- 它提供了與IE11等舊瀏覽器的向后兼容性
- 它將響應作為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獲得響應數據。數據沒有任何解析對象,不像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方法非常簡短,可以直接傳遞請求主體參數,這與fetch()API不同。
作者:Danny Markov 譯者:前端小智 來源:tutorialzine
原文:https://tutorialzine.com/2017/12-terminal-commands-every-web-developer-should-know
本文轉載自微信公眾號「大遷世界」,可以通過以下二維碼關注。轉載本文請聯系大遷世界公眾號。