ajax的核心API-XMLHttpRequest

簡易的ajax

get請求ajax

//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請求json

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-服務器端錯誤
相關文章
相關標籤/搜索