Bootstrap

Vue中如何实现ajax请求,vue.js中如何用promise实现for循环ajax调用?

function ajax(mode,url,data){

return new Promise(function(resolve,reject){

var request = new XMLHttpRequest();

request.open(mode,url,true);

console.log(postDataFormat(data))

request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");

request.send(postDataFormat(data));

request.onload = function(){

if((this.status >= 200 && this.status < 300) || this.status == 304){

resolve(this);

}else{

reject(this);

};

};

})

}

function postDataFormat(obj){

if(typeof obj != "object" ) {

alert("输入的参数必须是对象");

return;

}

var arr = new Array();

var i = 0;

for(var attr in obj) {

arr[i] = encodeURIComponent(attr) + "=" + encodeURIComponent(obj[attr]);

i++;

}

return arr.join("&");

}

//调用

ajax('POST','./1.php',{aaa:"aaa",bbb:"bbb"}).then((res)=>{

console.log(res.response);

return ajax('POST','./1.php',{aaa:"aaa1",bbb:"bbb1"});

}).then((res)=>{

console.log(res.response);

}).catch((res)=>{

console.log(res.statusText);

})

//当然,也可以用并行

Promise.all([ajax('POST','./1.php',{aaa:"aaa",bbb:"bbb"}),ajax('POST','./1.php',{aaa:"aaa1",bbb:"bbb1"})]).then(function(allres){

console.log(allres);

})

;