原生ajax
//创建异步对象
var xhr = new XMLHttpRequest();
//设置请求基本信息,并加上请求头
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.open('post', 'test.php' );
//发送请求
xhr.send('name=Lan&age=18');
xhr.onreadystatechange = function () {
// 这步为判断服务器是否正确响应
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
jqueryAjax
var loginBtn = document.getElementsByTagName("button")[0];
loginBtn.onclick = function(){
ajax({
type:"post",
url:"test.php",
data:"name=lan&pwd=123456",
success:function(data){
console.log(data);
}
});
}
fetch
fetch('http://www.mozotech.cn/bangbang/index/user/login', {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams([
["username", "Lan"],["password", "123456"]
]).toString()
})
.then(res => {
console.log(res);
return res.text();
})
.then(data => {
console.log(data);
})
axios
axios({
method: 'post',
url: '/abc/login',
data: {
userName: 'Lan',
password: '123'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
对比
几种方式的对比
ajax:
【优点:局部更新;原生支持】
【缺点:可能破坏浏览器后退功能;嵌套回调】
jqueryAjax:
【在原生的ajax的基础上进行了封装;支持jsonp】
fetch:
【优点:解决回调地狱】
【缺点:API 偏底层,需要封装;默认不带Cookie,需要手动添加; 浏览器支持情况不是很友好,需要第三方的ployfill】
axios:
【几乎完美】
axios
的特点
支持浏览器和node.js
支持promise
能拦截请求和响应
能转换请求和响应数据
能取消请求
自动转换JSON数据
浏览器端支持防止CSRF(跨站请求伪造)
如何将axios
异步请求同步化处理?
//使用 asyns/await
async getHistoryData (data) {
try {
let res = await axios.get('/api/survey/list/', {
params: data
})
this.tableData = res.data.result
this.totalData = res.data.count
} catch (err) {
console.log(err)
alert('请求出错!')
}
}