一个简单的请求例子
//创建对象
var xhr = new XMLHttpRequest();
//初始化
xhr.open('GET', 'https://api.test/json');
//设置请求头
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//发送请求
xhr.send();
//处理相应结果
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) | 规定请求的类型、URL 以及是否异步处理请求<br />method:请求的方法post或get<br />url:请求的地址<br />async:true(异步)或false(同步)一般就默认true不写 |
setRequestHeader(header,value) | 向请求添加 HTTP 头。<br />header:规定头的名称<br />value:规定头的值 |
send(string) | 将请求发送到服务器。<br />string:仅用于 POST 请求 |
onreadystatechange | 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。 |
readyState
存有 XMLHttpRequest
的状态
- 0: 请求未初始化
- 1: 服务器连接已建立
- 2: 请求已接收
- 3: 请求处理中
- 4: 请求已完成,且响应已就绪
可以观察上面的console.log(xhr.readyState)
输出了三次分别为2,3,4
演示个POST类型的请求
//创建对象
var xhr = new XMLHttpRequest();
//初始化
xhr.open('POST', 'https://test.api/post');
//设置请求头
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//发送请求
xhr.send('keya=123&keyb=321');
//处理相应结果
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)
})