以前的ajax大多使用的还是jquery自带的ajax方法。实际也是根据原生的ajax实现的,但是以前的ajax大多使用的是回调函数的方式处理异步,如果要实现多重异步,就会产生回调地狱。对代码的可读性非常不好,因此这里我们重新使用promise实现一个异步,不会产生回调地狱。
function ajax(url,type="get"){ return new Promise((resolve,reject)=>{ let xhr = new XMLHttpRequest(); xhr.open(type,url) xhr.send() xhr.onload=function(){ if(this.status==200){ resolve(JSON.parse(this.response)) }else{ reject("加载失败") } } xhr.onerror=function(){ reject(this) } }) }
这是一个封装的ajax方法,返回一个promise对象
所以我们调用:
ajax("./json/1.json").then(data=>{ console.log(1,data) return ajax("./json/2.json?a="+data.a) }).then(data=>{ console.log(2,data) })
记住,此处第二次调用ajax时要使用return,才能在下方的then进行处理。
这样就不会造成回调地狱了