【XMLHttprequest】手寫一個簡易的ajax

GET 請求
// 創建XMLHttpRequest對象
const xhr=new XMLHttpRequest()
// 創建一個 get 請求,true 採用異步
xhr.open('GET','./test.json',true)
xhr.onreadystatechange=function(){
    if (xhr.readyState === 4) {
        if (xhr.status=== 200) {
            alert(xhr.responseText)
        }
    }
}
//發送請求
xhr.send(null)
POST 請求
// 創建XMLHttpRequest對象
const xhr = new XMLHttpRequest()
// 創建一個 get 請求,true 採用異步
xhr.open('POST', './test.json', true)
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            alert(xhr.responseText)
        }
    }
}
//發送請求
const postData={
    userName:'zhangsan',
    password:'xxx'
}
xhr.send(JSON.stringify(postData))//發送格式爲json字符串

XMLHttpRequest的readyState和status

xhr.readyState

0: 請求未初始化: 還沒有調用 open()。
1: 請求已經建立: 但是還沒有發送, 還沒有調用 send()。
2: 請求已發送: 正在處理中( 通常現在可以從響應中獲取內容頭)。
3: 請求在處理中: 正在解析響應內容
4: 響應已完成: 內容解析完成,可以在客戶端調用

xhr.status

1 xx - 信息提示.
2 xx - 成功 服務器成功地接受了客戶端請求.
3 xx - 重定向,瀏覽器直接跳轉
4 xx - 客戶端錯誤 (客戶端請求不存在的頁面,客戶端未提供有效的身份驗證信息。).
5 xx - 服務器錯誤 服務器由於遇到錯誤而不能完成該請求.

常見

200 - OK 一切正常,對GET和POST請求的應答文檔跟在後面.
300 - Multiple Choices 客戶請求的文檔可以在多個位置找到.
301 - Moved Permanently 永久重定向.
302 - Found 臨時重定向.
304 - Not Modified 資源未改變,使用緩存的資源.
400 - Bad Request 請求出現語法錯誤。
403 - Unauthorized 沒有權限訪問,訪問被拒絕.
404 - Not Found 請求地址有錯誤.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章