文章目录
前言
在正式了解“回调地狱”之前,我们先了解两个概念:
-
回调函数
当一个函数作为参数传入另一个参数中,并且它不会立即执行,只有当满足一定条件后该函数才可以执行,这种函数就称为回调函数。我们熟悉的定时器和Ajax中就存在有回调函数:setTimeout(function(){ //function(){console.log(‘执行了回调函数’)}就是回调函数,它只有在3秒后才会执行
console.log(‘执行了回调函数’);
},3000) //3000毫秒
这里的回调函数是function(){console.log('执行了回调函数')}
,在满足时间3秒后执行。
//1.创建异步对象
var xhr=new XMLHttpRequest();
//2.绑定监听事件(接收请求)
xhr.onreadystatechange=function(){
//此方法会被调用4次
//最后一次,readyState==4
//并且响应状态码为200时,才是我们要的响应结果 xhr.status==200
if(xhr.readyState==4 && xhr.status==200){
//把响应数据存储到变量result中
var result=xhr.responseText;
console.log(result);
}
}
//3.打开链接(创建请求)
xhr.open("get","/demo/ajaxDemo",true);
//4.发送请求
xhr.send();
这里的回调函数是xhr.onreadystatechange
绑定的函数,在x