Ajax
之前的实现AJAX的方式:
XMLHttpRequest
IE7及以上版本支持,老版本用ActiveXObject
超时时间(毫秒)
请求的状态码,完整的可以参考:HTTP响应状态码
响应状态,如 '200 OK'
值 | 状态 | 描述 |
---|---|---|
0 | UNSENT | 创建但还未调用open() |
1 | OPENED | open方法被调用 |
2 | HEADERS_RECEIVED | send被调用,并且头部和状态可获得 |
3 | LOADING | 下载中;responseText包含部分数据 |
4 | DONE | 操作完成 |
定义响应类型
响应值
open(method, url, async)
初始化请求
发送请求,string用在post请求,发送数据
添加http头
readyState属性发生变化时调用
const xhr = new XMLHttpRequest;
// xhr.readyState 0
xhr.open('GET', './xxx.json', true);
// xhr.readyState 1
xhr.timeout = 2000;
xhr.onprogress = function () {
// xhr.readyState 3
}
xhr.onload = function() {
const data = JSON.parse(this.responseText);
console.log(data);
// xhr.readyState 4
}
xhr.ontimeout = function (e) {
// 超时
};
xhr.onerror = function(err) {
console.log(err);
}
xhr.send();
// post
xhr.open('POST', 'xxx.asp', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send('name=test&value=123');
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.response); // 响应正文
console.log(xhr.responseText);
console.log(xhr.responseXML)
}
}
Fetch
基于Promise,写起来看着是这样:
get请求
fetch(url)
.then(res => res.text())
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
post请求
fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: 'name=hello&value=world',
credentials: 'include'
})
.then(res => res.json())
.then(res => { console.log(res) })
.catch(error => { console.log(error) });
可以设置:
method 请求方法,GET | POST
headers 请求相关的headers对象
body 请求正文
credentials 是否发送cookie,有三个值:
+ omit 从不发送
+ same-origin 同源发送
+ include 总是发送,无论是否同源
返回response
对响应正文可以使用text()或json()方法,返回Promise;
其他处理方法还有blob() arrayBuffer()和 formData();
可以和async/await一起这么玩
async function fetchData() {
const fetchRes = fetch(url);
const res = await fetchRes;
console.log('one')
const data = await res.json();
console.log(data)
}
fetchData();
使用fetch时,不会携带cookie信息,需要的话要设置credentials
fetch(url, {
credentials: 'include'
})
服务端返回404或500之类的状态,也还是会执行到promise的resolve中,不会在catch里,所以需要自己判断...
fetch(myRequest)
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error('Something went wrong on api server!');
}
})
.then(response => {
// ...
}).catch(error => {
// ...
});
对于不支持的浏览器,可以使用:
当然不支持Promise的还要再拉一个Promise Polyfill...
参考: