1. 前后端交互模式
2. Promise用法
2.4基于Promise处理Ajax请求
发送多次ajax请求
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
</div>
</body>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" >
/*
2.4基于Promise处理Ajax请求
发送多次ajax请求
*/
function queryData(url){
var p = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState != 4)return;
if(xhr.readyState == 4 && xhr.status == 200){
//处理正常的情况
resolve(xhr.responseText);
}else {
//处理异常情况
reject('服务器错误');
}
};
xhr.open('GET', url);
xhr.send(null);
});
return p;
}
// queryData('http://localhost:8090/sysUser/getList').then(function(data){
// console.log(data);
// },function(info){
// console.log(info);
// });
//**************************
//发送多个ajax请求,并且保证顺序
var url1 = 'http://localhost:8090/sysUser/getList';
var url2 = 'http://localhost:8090/sysUser/getUser/100';
var url3 = 'http://localhost:8090/sysUser/getUser/1';
queryData(url1).
then(function(data){
console.log(data);
return queryData(url2);
})
.then(function(data2){
console.log(data2);
return queryData(url3);
})
.then(function(data3){
console.log(data3);
})
var vm = new Vue({
el:'#app',
data:{
msg: "hello",
},
methods: {
handle: function (event) {
}
}
});
</script>
</html>
2.5then参数中的函数返回值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
</div>
</body>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" >
/*
2.5then参数中的函数返回值
1.返回Promise实例对象
返回的该实例对象会调用下一个then
2.返回普通值
返回的普通值会直接传递给下一个then,通过then参数中函数的参数接收该值
*/
function queryData(url){
var p = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState != 4) return;
if(xhr.readyState == 4 && xhr.status == 200){
resolve(xhr.responseText);
}else {
reject('服务器错误');
}
}
xhr.open('GET', url);
xhr.send(null);
});
return p;
}
var url1 = 'http://localhost:8090/sysUser/getList';
var url2 = 'http://localhost:8090/sysUser/getUser/100';
queryData(url1)
.then(function(data){
console.log(data);
return queryData(url2);
})
.then(function(data2){
console.log(data2);
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve('延迟3s')
}, 3000)
});
})
.then(function(data3){
console.log(data3);
return 'hello';
})
.then(function(data4){
console.log(data4);
})
var vm = new Vue({
el:'#app',
data:{
msg: "hello",
},
methods: {
handle: function (event) {
}
}
});
</script>
</html>