1. 程式人生 > >AJAX:二、XMLHttpRequest實踐

AJAX:二、XMLHttpRequest實踐

XHR(XMLHttpRequest) 實踐

簡介

XMLHttpRequest(通常縮寫XHR) 是一個 API,它為客戶端提供了在客戶端和伺服器之間傳輸資料的功能。它提供了一個通過 URL 來獲取資料的簡單方式,並且不會使整個頁面重新整理。這使得網頁只更新一部分頁面而不會打擾到使用者。XMLHttpRequest 在 AJAX 中被大量使用。

Fetch API 提供了一個獲取資源的介面(包括跨域)。

XHR

第一步,建立http請求

warning!: 本文已不再處理ie6-xhr物件的相容性問題

建立一個http請求也是需要提前做一些準備工作的。

  • 首先,就是要建立一個xhr物件,這是我們實現AJAX的核心。
// 建立一個xhr物件
const xhr = new XMLHttpRequest()

console.log('test', xhr)

建立完這個物件之後,我們可以在控制檯看到這個物件的詳細資訊了。

這裡寫圖片描述

  • 其次,必須提前宣告一個接收服務端資料的處理函式
// 建立一個xhr物件
const xhr = new XMLHttpRequest()

// 宣告函式,處理服務端的響應資料
xhr.onreadystatechange = res =>{
  console.log('res'
, res) } console.log('test', xhr)
  • 宣告完處理函式之後,我們需要設定http請求的相關引數
// 建立一個xhr物件
const xhr = new XMLHttpRequest()

// 宣告函式,處理服務端的響應資料
xhr.onreadystatechange = res =>{
  console.log('res', res)
}
// 向伺服器請求目標url中的資料檔案
xhr.open('GET', 'http://yyweb.yystatic.com/pc/images/default_portrait.png?20160616', true
) xhr.send()

此時,我們可以看到處理伺服器的回撥函式(onreadystatechange),一共被執行了四次。

這裡寫圖片描述

為什麼會呼叫四次?我們後面會講到。

第二步,處理服務端資料

通過第一步,我們就可以通過瀏覽器傳送最基本的request請求了。接下來,我們就準備處理從服務端獲取到的資料資訊了。

還記得,上面我們曾經宣告過的onreadystatechange函式嗎?這就是我們用來處理服務端資料的函式。那麼,我們應該如何正確處理這些資料請求呢?

我們先來看下面的程式碼,xhr.onreadystatechange函式中xhr物件的幾種狀態。


// 建立一個xhr物件
const xhr = new XMLHttpRequest()

// 宣告函式,處理服務端的響應資料
xhr.onreadystatechange = res =>{
  console.log(`res: ${res}, status: ${xhr.status}, readyState: ${xhr.readyState}`)
}
// 向伺服器請求目標url中的資料檔案
xhr.open('GET', 'http://yyweb.yystatic.com/pc/images/default_portrait.png?20160616', true)

xhr.send()


我們可以看到,xhr.readyState 返回了四種不同的狀態。

下面,就來介紹一下這四種狀態的含義:

  • 0 request請求還未初始化
  • 1 loading 或者與伺服器連線中
  • 2 loaded 或者伺服器接收到request請求
  • 3 建立連線或者服務端處理request
  • 4 建立完畢或者請求處理完成準備傳送response

xhr.status 200代表服務端成功接收到請求。

這裡寫圖片描述

瞭解完以上概念之後,我們再來梳理下面的邏輯

// 建立一個xhr物件
const xhr = new XMLHttpRequest()

// 宣告函式,處理服務端的響應資料
xhr.onreadystatechange = res =>{
  console.log(`status: ${xhr.status}, readyState: ${xhr.readyState}`)
  if (xhr.status === 200) {
    // 服務端狀態碼: 200 ok 表示請求成功
    if (xhr.readyState === 4) {
      // 準備接收服務端資料
      console.log(`status: ${xhr.readyState}, res: ${JSON.stringify(res)}`)
    }
  } else {
    // 0: 準備傳送請求
    // 400 Not Found or 500 服務端錯誤
  }
}
// 向伺服器請求目標url中的資料檔案
xhr.open('GET', 'http://yyweb.yystatic.com/pc/images/default_portrait.png?20160616', true)

xhr.send()

最終,我們成功發起請求從服務端獲取了一張圖片資料。

這裡寫圖片描述

第三步,封裝AJAX

為了日常開發使用,我們將AJAX封裝成一個函式庫,便於今後可以隨時使用。

  • 首先,進行最基本的包裝。將我們上述的程式碼放入到一個函式中進行簡單封裝。
const ajax = () => {
  // 建立一個xhr物件
  const xhr = new XMLHttpRequest()

  // 宣告函式,處理服務端的響應資料
  xhr.onreadystatechange = res =>{
    console.log(`status: ${xhr.status}, readyState: ${xhr.readyState}`)
    if (xhr.status === 200) {
    // 服務端狀態碼: 200 ok 表示請求成功
      if (xhr.readyState === 4) {
      // 準備接收服務端資料
        console.log(`status: ${xhr.readyState}, res: ${JSON.stringify(res)}`)
      }
    } else {
    // 0: 準備傳送請求
    // 400 Not Found or 500 服務端錯誤
    }
  }
  // 向伺服器請求目標url中的資料檔案
  xhr.open('GET', 'http://yyweb.yystatic.com/pc/images/default_portrait.png?20160616', true)

  xhr.send()

}

ajax()
  • 然後,為了讓我們封裝的ajax庫能夠適配各種生產環境,這就需要我們動態傳入引數進行配置。