一個(gè)簡(jiǎn)單的請(qǐng)求例子
//創(chuàng)建對(duì)象
var xhr = new XMLHttpRequest();
//初始化
xhr.open('GET', 'https://api.test/json');
//設(shè)置請(qǐng)求頭
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//發(fā)送請(qǐng)求
xhr.send();
//處理相應(yīng)結(jié)果
xhr.onreadystatechange = function () {
console.log(xhr.readyState)
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(xhr.response)
} else {
console.log(xhr.status)
}
}
}
方法 | 描述 |
---|---|
open(method,url,async) | 規(guī)定請(qǐng)求的類型闰挡、URL 以及是否異步處理請(qǐng)求<br />method:請(qǐng)求的方法post或get<br />url:請(qǐng)求的地址<br />async:true(異步)或false(同步)一般就默認(rèn)true不寫 |
setRequestHeader(header,value) | 向請(qǐng)求添加 HTTP 頭。<br />header:規(guī)定頭的名稱<br />value:規(guī)定頭的值 |
send(string) | 將請(qǐng)求發(fā)送到服務(wù)器择吊。<br />string:僅用于 POST 請(qǐng)求 |
onreadystatechange | 存儲(chǔ)函數(shù)(或函數(shù)名)又厉,每當(dāng) readyState 屬性改變時(shí)菠镇,就會(huì)調(diào)用該函數(shù)。 |
readyState
存有 XMLHttpRequest
的狀態(tài)
- 0: 請(qǐng)求未初始化
- 1: 服務(wù)器連接已建立
- 2: 請(qǐng)求已接收
- 3: 請(qǐng)求處理中
- 4: 請(qǐng)求已完成禀梳,且響應(yīng)已就緒
可以觀察上面的console.log(xhr.readyState)
輸出了三次分別為2,3,4
演示個(gè)POST類型的請(qǐng)求
//創(chuàng)建對(duì)象
var xhr = new XMLHttpRequest();
//初始化
xhr.open('POST', 'https://test.api/post');
//設(shè)置請(qǐng)求頭
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//發(fā)送請(qǐng)求
xhr.send('keya=123&keyb=321');
//處理相應(yīng)結(jié)果
xhr.onreadystatechange = function () {
console.log(xhr)
}
使用promise封裝Ajax演示demo
function sendAjax(url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response)
} else {
reject(xhr.status)
}
}
}
})
}
sendAjax('https://api.test/json').then((res) => {
console.log(res)
}, (err) => {
console.log(err)
})