开发过程中,我们向服务端发送请求,一般会使用三种方式, XMLHttpRequest(XHR),jQuery实现的AJAX,Fetch ,让我们首先来比较一下这三者的使用示例。
XMLHttpRequest
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
}
if (xhr) {
xhr.onreadystatechange = onReadyStateChange;
xhr.open('POST', '/api', true);
// 设置 Content-Type 为 application/x-www-form-urlencoded
// 以表单的形式传递数据
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('username=admin&password=root');
}
// onreadystatechange 方法
function onReadyStateChange() {
// 该函数会被调用四次
console.log(xhr.readyState);
if (xhr.readyState === 4) {
// everything is good, the response is received
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('There was a problem with the request.');
}
} else {
// still not ready
console.log('still not ready...');
}
}
从上边的代码可以看出,XMLHttpRequest 是一个非常粗糙的API,不符合关注分离(Separation of Concerns)的原则,配置和调用方式非常混乱,前端程序员们不仅要做各个浏览器的兼容性,还饱受回调地狱的折磨,这显然不是一个好的选择。
jQuery实现AJAX
$.ajax({
method: 'POST',
url: '/api',
data: { username: 'admin', password: 'root' }
})
.done(function(msg) {
alert( 'Data Saved: ' + msg );
});
jQuery作为一个使用人数最多的库,其AJAX很好的封装了原生AJAX的代码,在兼容性和易用性方面都做了很大的提高,而且jQuery还把jsonp装在了AJAX里面,这样我们就可以开心的跨域了!!!!对比原生AJAX的实现,使用jQuery实现的AJAX就异常简单了.
但是,笔锋一转,我们仍然逃脱不了一个问题,回调地狱。。。。
Fetch
fetch(...).then(fun2)
.then(fun3) //各依赖有序执行
.....
.catch(fun)
从上边的代码可以看出,fetch用起来想jQuery一样简单,虽然还是有Callback的影子,但是看起来舒服多了
详解Fetch API
兼容性
注意:由于Fetch API是基于Promise设计,旧浏览器不支持Promise,需要使用pollyfill es6-promise
- Fetch使用说明
fetch(url, options).then(function(response) {
// handle HTTP response
}, function(error) {
// handle network error
})
说明:
a. fetch api返回的是一个promise对象
b.Options:
- method(String): HTTP请求方法,默认为
GET
- body(String): HTTP的请求参数
- headers(Object): HTTP的请求头,默认为{}
- credentials(String): 默认为
omit
,忽略的意思,也就是不带cookie;还有两个参数,same-origin
,意思就是同源请求带cookie;include
,表示无论跨域还是同源请求都会带cookie
fetch('https://www.baidu.com/search/error.html', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
}),
body: new URLSearchParams([["foo", 1],["bar", 2]]).toString()
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
请求头中:get方法通过Accept指定获取的数据类型,post通过Content-type指定发送数据的类型,通过credentials设置cookie
axios
axios是通过promise实现对ajax技术的一种封装,就像jQuery实现ajax封装一样。
简单来说: ajax技术实现了网页的局部数据刷新,axios实现了对ajax的封装。
axios是ajax ajax不止axios