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

發出 HTTP 請求
透過創建(new)一個 XMLHttpRequest 物件,之後透過該物件中的 open(method, url, async) 及 send() 來確實發出請求。
//創建 XMLHttpRequest() 物件
const httpRequest = new XMLHttpRequest()
// 初始化一個請求
// 決定以何方法來透過API跟伺服器聯絡
httpRequest.open('GET','https://jsonplaceholder.typicode.com/todos/1',true)
//確實以 open() 要求來傳送請求
httpRequest.send()
open() 使用說明
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 不同值的意義。

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事件,httpRequest的load事件等於httpRequest.readyState === 4。
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 狀態碼。

httpRequest.addEventListener('load',()=>{
console.log(httpRequest,httpRequest.readyState) // 4
if(httpRequest.status === 200){
//回傳的資料內容
console.log(httpRequest.responseText)
}else{
//回傳的資料出了錯誤
//處理錯誤
}
})
參考資料
NDN - Synchronous and asynchronous requests
NDN - XMLHttpRequest.readyState

















