有一个ajax请求需要在三个ajax请求之后发起,其中之前的三个ajax可以并行,如何优雅的实现这种写法?-灵析社区

万码F5GTP6P0

我有一个接口,需要在三个接口都调用成功之后执行,不知道怎么写

阅读量:135

点赞量:0

问AI
用promise呀 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("&"); } // 用并行 Promise.all([ajax('POST','./1.php',{aaa:"aaa",bbb:"bbb"}),ajax('POST','./1.php',{aaa:"aaa1",bbb:"bbb1"})]).then(function(allres){ console.log(allres);//三个请求的返回的集合 ajax('POST','./1.php',{XXXX}).then();})