3-1 Ajax原理与Callback Hell

57 阅读1分钟

JS是单线程的 一个时间只能处理一个任务,

在进行网页开发的时候主要用到html css js ,

js是用来与用户的一些互动交互以及操作DOM结构,

假设一个线程进行增加的操作,另外一个线程进行删除的操作,对于网页来说就不知道该先执行哪个了,为了避免这些问题,JS在设计初期的时候,设计成单线程的

const a = 2
const b = 3
console.log(a + b)  // 同步
setTimeout(()=>{
  console.log(a + b)  // 异步
},1000)


console.log(1)
setTimeout(()=>{
  console.log(2)
}, 0)
console.log(3)

// 1  3  2

流程图.jpg

  • Ajax 原理
  • 在不重新加载页面的情况下局部刷新数据
// 1.创建XmlHttpRequest对象
var url = ''
var xmlhttp 
if(window.XmlHttpRequest){
  xmlhttp = new XmlHttpRequest()
} else {
  xmlhttp = new AxtiveXObject('Microsoft.XMLHTTP')
}
// 2.发送请求
xmlhttp.open('GET', url, true)
xmlhttp.send()
// 3.服务端响应
xmlhttp.onreadystatechange = function() {
  if(xmlhttp.readyState === 4 &&& xmlhttp.status === 200){
    var obj = JSON.parse(xmlhttp.responseText)
    console.log(obj)
  }
}
  • ajax 实例
function ajax(url, callback){
  var xmlhttp 
  // 做浏览器判断
  if(window.XmlHttpRequest){
    xmlhttp = new XmlHttpRequest()
  } else {
    xmlhttp = new AxtiveXObject('Microsoft.XMLHTTP')
  }
  2.发送请求
  xmlhttp.open('GET', url, true)
  xmlhttp.send()
  3.服务端响应
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState === 4 &&& xmlhttp.status === 200){
      var obj = JSON.parse(xmlhttp.responseText)
      callback(obj)
    }
  }
}
var url = ''
ajax(url, res => {
  console.log(res)
})

Callback Hell // 回调地狱 我们希望在完成 Ajax 第一步之后再完成第二步,第三步, 三个文件是有依赖关系的,比如省市县三级联动 a.json

{
  "a": "我是a"
}

b.json

{
  "b": "我是b"
}

c.json

{
  "c": "我是c"
}
function ajax(url, callback){
  // 做浏览器判断
  if(window.XmlHttpRequest){
    xmlhttp = new XmlHttpRequest()
  } else {
    xmlhttp = new AxtiveXObject('Microsoft.XMLHTTP')
  }
  2.发送请求
  xmlhttp.open('GET', url, true)
  xmlhttp.send()
  3.服务端响应
  xmlhttp.onreadystatechange = function() {
    if(xmlhttp.readyState === 4 &&& xmlhttp.status === 200){
      var obj = JSON.parse(xmlhttp.responseText)
      callback(obj)
    }
  }
}
ajax('a.json',res => {
  console.log(res) 
  ajax('b.json', res => {
    console.log(res)
    ajax('c.json', res => {
      console.log(res)
      // 虽然res 名字一样,js 在查找的时候会优先在当前作用域以内查找,如果找不到在往外面查找
    })
  })
})