溫馨提示×

溫馨提示×

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

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

JavaScript怎么進行AJAX調(diào)用和請求

發(fā)布時間:2022-05-07 14:41:01 來源:億速云 閱讀:226 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹了JavaScript怎么進行AJAX調(diào)用和請求的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇JavaScript怎么進行AJAX調(diào)用和請求文章都會有所收獲,下面我們一起來看看吧。

1.AJAX

術(shù)語AJAX 表示 異步的 JavaScript 和 XML

AJAX 在 JS 中用于發(fā)出異步網(wǎng)絡(luò)請求來獲取資源。當然,不像名稱所暗示的那樣,資源并不局限于XML,還用于獲取JSON、HTML或純文本等資源。

2.XMLHttpRequest

XMLHttpRequest對象(簡稱XHR)在較早的時候用于從服務(wù)器異步檢索數(shù)據(jù)。

之所以使用XML,是因為它首先用于檢索XML數(shù)據(jù)?,F(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è)置請求標頭“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ù)

1、url是必填參數(shù),它是您要獲取的資源的路徑。

2、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)碼(如200404、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.2 示例: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

錯誤處理

我們來看看當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不同。

關(guān)于“JavaScript怎么進行AJAX調(diào)用和請求”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“JavaScript怎么進行AJAX調(diào)用和請求”知識都有一定的了解,大家如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

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

AI