<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>手寫ajax</title> </head> <body> <script> const xhr = new XMLHttpRequest(); xhr.open('GET', '/api', false); xhr.onreadystatechange = function () { // xhr.readyState 的各個狀態 // 0:未初始化,還沒有呼叫send()方法 // 1:載入,已呼叫send()方法,正在發送請求 // 2:載入完成,send()方法執行完成,已經接收到全部回應內容 // 3:互動,正在決議回應內容 // 4:完成,回應內容決議完成,可以再客戶端呼叫 if(xhr.readyState == 4){ // status狀態碼分類: // 1xx:服務器收到請求 // 2xx:請求成功 // 3xx:重定向 // 4xx:客戶端錯誤 // 5xx:服務端錯誤 if(xhr.status == 200){ // 常見狀態: // 200:成功 // 301:永久重定向 // 302:臨時重定向 // 304:資源未被修改 // 404:資源未找到 // 403:沒有權限 // 500:服務器錯誤 // 504:網關超時 alert(xhr.responseText) } } } xhr.send(null) xhr.open('POST','/api',false) const postData={ userName:'zhangsan', password:'abc123' } xhr.send(JSON.stringify(postData)) </script> </body> </html>
考點:
1、XMLHttpRequest的使用
2、XMLHttpRequest狀態碼
3、常見請求狀態碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/14886.html
標籤:JavaScript
上一篇:作用域那點事
下一篇:前端面試題整理——陣列去重
