比较之后,在不同场合选取不同的调取方法
1: jquery ajax
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: dataType,
headers: {userToken:token},
success: function() {},
error: function() {},
})
优缺点:
- 本身是针对MVC的编程,不符合现在前端的MVVM模式
- 基于源生的XHR开发,XHR本身的架构不清晰,已经有了fetch作为替代
- jquery 整个项目比较大,单纯使用ajax却要引入整个jquery非常不合理,采用地址引入的方式不能定死版本,容易出现兼容问题
- 容易出现回调地狱
2:axios
axios({
method: 'POST',
url: url,
data: {},
headers: {},
})
.then(functon (response) {
console.log(response)
})
.catch(function(error)) {
consol.log(error)
}
优缺点:
- 从node.js 创建http请求
- 支持Promise API
- 客户端支持防止CSRF
- 提供了一些并发请求的接口
3: fetch
fetch api 是基于promise的设计。他是为了取代传统的xhr不合理的写法而产生的
xhr 请求写起来混乱 如下所示
var xhr = new XMLHttpRequst();
xhr.open('GET',url);
xhr.responseType = 'json';
xhr.onload = function() {
console.log(xhr.response);
}
xhr.onerror = function() {
console.log('Oops',error);
}
xhr.send();
fetch 在xhr的基础上修改之后,清晰而直接
fetch(url).then(function(response){
return response.json();
}).then(function(data) {
console.log(data);
}).catch(function(e) {
console.log('Oops,error')
})
fetch使用箭头函数将会更加简洁
fetch(url).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log('Oops',error',e))
但是,使用promise,还是可以很明显的看到callback的使用,这时候可以使用aysnc和await
async function fetchAsync(){
let response = await fetch('https://api.github.com');
let data = await response.json();
return data;
}
注意:
1:fetch()返回的是一个Promise对象 fetch使用的promise对象市一是的我们使用同步的方式写异步函数
2:fetch api 是可以结合async和await来使用的
fetch是基于promise实现的,但是使用promise的写法,还是能看到callback的影子,结合async和await后效果非常好
3:fetch api 可以跨域
fetch('http://localhost:6888/test_get',{
method: 'GET',
mode: 'cors',//跨域设置
}).then(res => {
return res.json()
}).then(json => {
console.log('获取的结果',json.data)
return json;
}).catch(err => {
console.log('请求错误',err)
})