目录
原理:
JavaScipt 中的许多操作都是异步的,我们把上面的Ajax封装成一个函数:
实例:
function ajax(url, callback) {
let xmlhttp
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest()
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
// 发送请求
xmlhttp.open("GET", url, true)
xmlhttp.send()
// 服务端响应
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// console.log(xmlhttp.responseText)
let obj = JSON.parse(xmlhttp.responseText)
callback(obj)
}
}
}
回调地狱:
我们在static文件夹下放入三个json文件:
a.json:
{
"a": "我是A"
}
b.json:
{
"b": "我是B"
}
c.json:
{
"c": "我是C"
}
我们可以像这样使用:
// 加载并执行脚本
ajax('/static/a.json')
函数是异步调用的,因为操作不是立即完成的,而是之后才会完成。
ajax('/static/a.json')
// 下面的代码不会等到ajax执行完才执行
这个过程大家并不陌生,可是如果在回调之后再回调呢?
ajax('static/a.json', res => {
console.log(res)
ajax('static/b.json', res => {
console.log(res)
ajax('static/c.json', res => {
console.log(res)
})
})
})
如果嵌套变多,代码层次就会变深,维护难度也随之增加。
这就被称为 “回调地狱” 或者“回调深渊”。