溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

在 JS 中怎么使用 Ajax 來(lái)進(jìn)行請(qǐng)求

發(fā)布時(shí)間:2021-07-22 09:48:43 來(lái)源:億速云 閱讀:179 作者:chen 欄目:web開(kāi)發(fā)

本篇內(nèi)容介紹了“在 JS 中怎么使用 Ajax 來(lái)進(jìn)行請(qǐng)求”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

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è)偵聽(tīng)器來(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

早期的開(kāi)發(fā)人員,已經(jīng)使用了好多年的 XMLHttpRequest來(lái)請(qǐng)求數(shù)據(jù)了。現(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ù)沒(méi)有任何解析對(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不同。

“在 JS 中怎么使用 Ajax 來(lái)進(jìn)行請(qǐng)求”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI