簡易的ajax
get請求
//get請求
const xhr = new XMLHttpRequest()
xhr.open("GET","/api",false)//false表示請求方式為異步
xhr.onreadystatechange = function () {
if(xhr.readyState === 4){
if(xhr.status === 200){
console.log(JSON.parse(xhr.responseText))//轉化成json格式
}
}
}
xhr.send(null)
post請求
const xhr = new XMLHttpRequest()
xhr.open("POST","/login",false)
xhr.onreadystatechange = function () {
if(xhr.readyState === 4){
if(xhr.status === 200){
console.log(JSON.parse(xhr.responseText))
}
}
}
const postData = {
username:'張三',
password:'123456'
}
xhr.send(JSON.stringify(postData))//發送字符串
xhr.readyState狀態
- 0-(未初始化)還沒有調用send()方法
- 1-(載入)已調用send()方法,正在發送請求
- 2-(載入完成)send()方法執行完成,已經接收到全部響應內容
- 3-(交互)正在解析響應內容
- 4-(完成)響應內容解析完成,可以在客户端調用
xhr.status
- 2xx-表示成功處理請求,如200
- 3xx-重定向,瀏覽器直接跳轉,如301(永久重定向),302(臨時重定向),304(資源未改變)
- 4xx-客户端請求錯誤,如404(請求地址有錯誤),403(客户端沒有權限)
- 5xx-服務器端錯誤