目錄
- 前言
- 1、實作步驟
- 1.1 創建 XMLHttpRequest 物件
- 1.2 通過 onreadystatechange 事件判斷請求是否成功
- 2.3 請求配置 open()
- 2.4 發送請求 send()
- 2、綜合演示
- 相關文章
前言
寫在前面的話:本篇文章主要講到的知識點是如何通過原生JavaScript 實作 Ajax,首先就需要對Json、HTTP網路傳輸協議、網路請求方式、異步編程等有一點點的了解;
1、實作步驟
- 創建
XMLHttpRequest物件;- 通過
onreadystatechange事件判斷請求是否成功;- 請求配置
open()- 發送請求
send()
1.1 創建 XMLHttpRequest 物件
XMLHttpRequest是一個建構式,創建該物件的實體化,可以使用建構式的方式:
let xhr; xhr = new XMLHttpRequest();現在很多的瀏覽器都已經有內置的 XMLHttpRequest 物件,但是為了兼容老版本的 瀏覽器,還有下面這個寫法:
let xhr; new ActiveXObject("Microsoft.XMLHTTP");
1.2 通過 onreadystatechange 事件判斷請求是否成功
在 Ajax 異步通信中,需要客戶端向后端發起請求,在這個程序中會涉及到 TCP 協議中的 三次握手四次揮手 規則;
使用 XMLHttpRequest 的onreadystatechange事件可以判斷當前事務的請求進度以及請求狀態xhr.onreadystatechange = function(){ if(xhr.readyState != 4){ // 當 readyState 值等于 4 的時候 請求完成 return } if(xhr.status == 200){ // 當 status 的值等于 200 的時候,請求成功 console.log(xhr.resposeText); // 收到后端回傳的資料 } else { console.log("請求失敗", xhr); } }
2.3 請求配置 open()
前端向后端發送請求需要使用到 XMLHttpRequest 物件中的 open() 方法進行請求配置:
xhr.open(method, url, async);引數解釋:
- method:請求方式(“POST”、“GET”、“HEAD”、“PUT”、“DELETE”);
- url:請求地址(通過與后端開發人員溝通后的介面檔案確定);
- async:布林值(是否異步請求,true代表 異步請求,false代表不使用異步請求,一般使用異步);
2.4 發送請求 send()
前端向后端發送請求則需要使用到 XMLHttpRequest 物件中的 send() 方法進行發送:
xhr.send(String);引數解釋:
- String:發送請求時,攜帶的資料資訊;
注意:
- 當請求型別為 “POST” 的時候,該引數是 “POST” 請求所攜帶的資料資訊(如果沒有資料資訊,也可以填寫 “null”);
- 當請求型別為 “GET” 型別的時候,該引數填寫為 “null” 因為,“GET” 請求型別的資料資訊是必須寫在 url 請求地址中的,并以 “?” 開頭,以 “&” 連接,如:?key=value&key=value
2、綜合演示
通過 Promise 物件處理 Ajax 的異步操作,關于XMLHttpRequest的 status值,網蟲找到一篇精簡版本的解釋說明:
- HTTP status 狀態碼(精簡版)
function myAjax({
method = "GET", // 請求方式設定默認為 GET 請求
url = null, // 請求路徑 默認為 null
data = null, // 攜帶的資料 默認為 null
async = true, // 默認為異步請求
timeout = 3000 // 請求時間
}) {
return new Promise((resolve, reject) => {
// ajax 實作步驟
let xhr;
// 兼容 判斷
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) { // 低版本 IE 處理
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
// 事件處理, 通過審核事件 onreadystatechange 來判斷請求成功與否
/*
* readyState 值:
* 0:未初始化,就是沒有呼叫 open();
* 1:啟動,已經呼叫 open(),但是沒有呼叫 send();
* 2:發送,呼叫 send(),但是沒有收到回應;
* 3:接收,回應體還沒有接收完成;
* 4:完成,接收到全部的回應資料,
*
* status值:
* xmlHttpRequest物件的status代表當前http請求的狀態,是一個長整型資料
*
*/
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) {
return
}
if (xhr.status == 200) {
console.log(JSON.parse(xhr.responseText))
// 因為默認接收的是 字串資料, 所以轉換為 Object 物件
resolve(JSON.parse(xhr.responseText))
} else {
// console.log("請求失敗", xhr)
reject(xhr)
}
}
// 設定請求超時
xhr.timeout = timeout;
// 將 GET 請求 與 POST 請求區分開
if (method === "GET") {
// 請求配置
// Get 請求引數必須放在 url 上,以 ?開頭, ?key=value&key=value
xhr.open(method, url + "?" + formatData(data), async)
// 發送請求
xhr.send(null)
} else if (method === "POST") {
// 請求配置
// POST 請求 可以不用寫 url 引數
xhr.open(method, async)
// POST 請求 需要設定請求頭 設定在 open 之后 send 之前
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencodeed")
//發送請求
//POST 在這里提交資料
xhr.send(formatData(data))
}
})
}
// 處理 get 請求的資料
// 對資料做處理,格式化成我們想要的資料: key=root&value=root
function formatData(data) {
if (data instanceof Object) {
let arr = []
for (let key in data) {
arr.push(key + "=" + data[key])
}
return arr.join("&")
}
return data
}
相關文章
- NodeJs - 模塊
……

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/340777.html
標籤:其他
上一篇:Vue:第一個vue-cli專案
