W3C官方文檔 https://www.w3school.com.cn/ajax/index.asp
MDN https://developer.mozilla.org/zh-CN/docs/Web/Guide/AJAX
1. 創(chuàng)建 XMLHttpRequest 對象
const xmlhttp=new XMLHttpRequest();
2. 向服務(wù)器發(fā)送請求
xmlhttp.open("GET","http://jsonplaceholder.typicode.com/posts",true);
xmlhttp.send();
-
open(method,url,async)
規(guī)定請求的類型、URL 以及是否異步處理請求辕棚。- method:請求的類型哈雏;
GET
或POST
- url:文件在服務(wù)器上的位置
- async:true(異步)或 false(同步)
- method:請求的類型哈雏;
-
send(string)
將請求發(fā)送到服務(wù)器- string:僅用于 POST 請求
3. GET還是POST
與 POST 相比茂缚,GET 更簡單也更快丸相,并且在大部分情況下都能用峻厚。
然而掂骏,在以下情況中理朋,請使用 POST 請求:
- 無法使用緩存文件(更新服務(wù)器上的文件或數(shù)據(jù)庫)
- 向服務(wù)器發(fā)送大量數(shù)據(jù)(POST 沒有數(shù)據(jù)量限制)
- 發(fā)送包含未知字符的用戶輸入時绩蜻,POST 比 GET 更穩(wěn)定也更可靠
GET請求
xmlhttp.open("GET",URL, true);
xmlhttp.send();
POST請求
如果需要像 HTML 表單那樣 POST 數(shù)據(jù)铣墨,請使用 setRequestHeader() 來添加 HTTP 頭。然后在 send() 方法中規(guī)定您希望發(fā)送的數(shù)據(jù):
xmlhttp.open("POST",URL,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=Jack&age=18");
setRequestHeader(header,value)
向請求添加 HTTP頭办绝。
- header: 規(guī)定頭的名稱
- value: 規(guī)定頭的值
4. 服務(wù)器響應(yīng)
- responseText 獲得字符串形式的響應(yīng)數(shù)據(jù),現(xiàn)在一般使用json數(shù)據(jù)格式伊约,一般使
responseText
。 - responseXML 獲得 XML 形式的響應(yīng)數(shù)據(jù)八秃。
5. onreadystatechange() 事件
當(dāng)請求被發(fā)送到服務(wù)器時碱妆,我們需要執(zhí)行一些基于響應(yīng)的任務(wù)。
每當(dāng) readyState 改變時昔驱,就會觸發(fā) onreadystatechange 事件疹尾。
readyState 屬性存有 XMLHttpRequest 的狀態(tài)信息。
onreadystatechange 存儲函數(shù)(或函數(shù)名),每當(dāng) readyState 屬性改變時纳本,就會調(diào)用該函數(shù)窍蓝。
-
readyState 存有 XMLHttpRequest 的狀態(tài)。從 0 到 4 發(fā)生變化繁成。
- 0: 請求未初始化
- 1: 服務(wù)器連接已建立
- 2: 請求已接收
- 3: 請求處理中
- 4: 請求已完成吓笙,且響應(yīng)已就緒
-
status
- 200: "OK"
- 404: 未找到頁面
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// 獲取服務(wù)器放回的json數(shù)據(jù),并轉(zhuǎn)換數(shù)據(jù)類型
console.log(JSON.parse(xmlhttp.responseText));
}
}
es6+Promise手寫ajax()函數(shù)
export function ajax({url,method,data,timeout}){
return new Promise((resolve, reject) => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open(method, url, true);
xmlhttp.timeout = timeout || 5000;
if(method === "GET"){
xmlhttp.send(null);
}else if(method === "POST"){
let queryList = [];
for(let key in data){
queryList.push(`${key}=${encodeURIComponent(data[key])}`);
}
let querys = queryList.join('&')
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(querys);
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.readyState,xmlhttp.status);
resolve(JSON.parse(xmlhttp.responseText))
}
}
})
}
導(dǎo)入
<script type="module">
import {ajax} from "./ajax.js"
ajax({
url:"http://jsonplaceholder.typicode.com/posts",
method:"GET",
timeout:4000,
}).then(res => {
console.log('ajax請求',res);
}).catch(err=>{
console.log(err);
})
</script>