EP 02 | Asynchronous JS 的運用 - HTTP Requests

先來了解一下一個專有名詞 「AJAX」(非同步 JavaScript 及 XML,Asynchronous JavaScript and XML),這個名詞主要用來描述利用 JS 中數個方法來向伺服器取得資料,且不需要更新畫面即可及時取得最新內容,而這一篇主要是介紹如何使用 XMLHttpRequest 來發出請求及接收回應的。

發出 HTTP 請求

透過創建(new)一個 XMLHttpRequest 物件,之後透過該物件中的 open(method, url, async)send() 來確實發出請求。

1
2
3
4
5
6
7
8
//創建 XMLHttpRequest() 物件
const httpRequest = new XMLHttpRequest()

// 初始化一個請求
// 決定以何方法來透過API跟伺服器聯絡
httpRequest.open('GET','https://jsonplaceholder.typicode.com/todos/1',true)
//確實以 open() 要求來傳送請求
httpRequest.send()

open() 使用說明

1
httpRequest.open(method, url, async)
  • method :可使用 GETPOSTPUTDELETE HEAD 來處理資料。

  • url : 欲請求頁面的 URL ,須小心有跨來源資源共用(CORS)的問題。

  • async : 是否為非同步,非同步為 true (默認值),同步為 false

接收 HTTP 請求

在發出請求後,經過一段時間會得到回傳的資料,這時候透過開發者工具即可看到資料回傳狀況及接收到的資料內容。

我們可以將處理資料的方法分為 2 個步驟:

監聽資料回傳狀況

監聽 XMLHttpRequest 物件中的 readyState 屬性變化來看資料是否已經回傳,而 readyState 屬性總共有幾個值分別代表不同意思,請參考下圖(擷取自 MDN)

在透過 XMLHttpRequest 發出請求後,有下列幾種方法可以用來監聽資料回傳進展狀況。

  • 監聽 XMLHttpRequest 物件中的 readyState
    須先了解 readyState 不同值的意義。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    httpRequest.addEventListener('readystatechange',()=>{
    console.log(httpRequest,httpRequest.readyState)
    //httpRequest.readyState === 4 代表資料已回傳完畢
    if(httpRequest.readyState === 4){
    //回傳的資料內容
    console.log(httpRequest.responseText)
    }
    })

    /*
    httpRequest.onreadystatechange = ()=>{
    console.log(httpRequest,httpRequest.readyState)
    //httpRequest.readyState === 4 代表資料已回傳完畢
    if(httpRequest.readyState === 4){
    //回傳的資料內容
    console.log(httpRequest.responseText)
    }
    }
    */
    • 監聽 load 事件,httpRequestload 事件等於 httpRequest.readyState === 4
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    httpRequest.addEventListener('load',()=>{
    console.log(httpRequest,httpRequest.readyState) // 4
    //回傳的資料內容
    console.log(httpRequest.responseText)
    })

    /*
    httpRequest.onload = ()=>{
    console.log(httpRequest,httpRequest.readyState) // 4
    //回傳的資料內容
    console.log(httpRequest.responseText)
    }
    */

接收到的資料狀態

當透過 httpRequest.readyState 確定資料已經回傳完畢後,這時候還得透過 httpRequest.status 來確認伺服器回傳回來的資料狀態是否正確。

httpRequest.status 也有幾種不同值,而每個值分別代表不同意思,詳細可參考HTTP 狀態碼

1
2
3
4
5
6
7
8
9
10
httpRequest.addEventListener('load',()=>{
console.log(httpRequest,httpRequest.readyState) // 4
if(httpRequest.status === 200){
//回傳的資料內容
console.log(httpRequest.responseText)
}else{
//回傳的資料出了錯誤
//處理錯誤
}
})

參考資料

NDN - AJAX 入門篇

NDN - 使用 XMLHttpRequest

NDN - Synchronous and asynchronous requests

NDN - XMLHttpRequest.readyState