EP 02 | Asynchronous JS 的運用 - HTTP Requests
先來了解一下一個專有名詞 「AJAX」(非同步 JavaScript 及 XML,Asynchronous JavaScript and XML),這個名詞主要用來描述利用 JS 中數個方法來向伺服器取得資料,且不需要更新畫面即可及時取得最新內容,而這一篇主要是介紹如何使用 XMLHttpRequest 來發出請求及接收回應的。
發出 HTTP 請求
透過創建(new
)一個 XMLHttpRequest
物件,之後透過該物件中的 open(method, url, async)
及 send()
來確實發出請求。
1 | //創建 XMLHttpRequest() 物件 |
open()
使用說明
1 | httpRequest.open(method, url, async) |
method
:可使用GET
、POST
、PUT
、DELETE
、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
19httpRequest.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
事件,httpRequest
的load
事件等於httpRequest.readyState === 4
。
1
2
3
4
5
6
7
8
9
10
11
12
13httpRequest.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 | httpRequest.addEventListener('load',()=>{ |
參考資料