10-1 原生ajax

  1. var url = "http://192.168.4.18:8000/"
  2. var xhr = new XMLHttpRequest();
  3. xhr.open("get", url, true);
  4. xhr.send();
  5. xhr.onreadystatechange = function () {
  6. if (xhr.readyState == 4 && xhr.status == 200) {
  7. var result = JSON.parse(xhr.responseText);
  8. console.log(result)
  9. }
  10. }

10-2 回调函数去封装ajax

  1. // 需要记住传参的顺序
  2. function ajax(url,method="get",success) {
  3. var xhr = new XMLHttpRequest();
  4. xhr.open(method, url, true);
  5. xhr.send();
  6. xhr.onreadystatechange = function () {
  7. if (xhr.readyState == 4 && xhr.status == 200) {
  8. var result = JSON.parse(xhr.responseText);
  9. success(result)
  10. }
  11. }
  12. }
function ajax({
  url,
  method="get",
  success
}) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.send();
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      var result = JSON.parse(xhr.responseText);
      success(result)
    }
  }
}

10-3 jquery-ajax

$.ajax({
  url:"http://192.168.4.18:8000/",
  type:"get",
  dataType:"json",
  success:res=>{
    console.log(res)
  }
})

10-4 callback封装jquery-ajax

function http({url,type="get",success}){
  $.ajax({
    url,
    type,
    dataType:"json",
    success:res=>{
      success(rs)
    }
  })
}

10-5 promise封装ajax

将纵向嵌套的ajax,变成横向的了,结构稍微清晰了一点。

function http(url){
  return new Promise((resolve,reject)=>{
    $.ajax({
      url,
      type:"get",
      success:res=>{
        resolve(res)
      },
      error:err=>{
        reject(err);
      }
    })
  })
}