封装AJAX

70 阅读1分钟

AJAX原始代码

//创建请求
const xhr = new XMLHttpRequest()

//初始化请求
xhr.open('GET', '/xxx')

//监听请求
xhr.onreadystatechange = () => {
  if (xhr.readyState === 4) {
    if (xhr.status >= 200 && xhr.status < 300) {
      console.log('请求成功,得到内容为:' + xhr.responseText)
    } else if (xhr.status >= 400) {
      console.log('请求失败,状态码为:' + xhr.status)
    }
  }
}

//发送请求
xhr.send()

封装AJAX函数

//const ajax = (method, url, body, success, fail) => {}
//参数太多了,把参数改成对象,析构赋值 
const ajax = ({ method, url, body, success, fail }) => {
  //如果传参数是obj,然后obj可以省略。直接传参数,析构赋值
  //const { method, url, body, success, fail } = obj
  const xhr = new XMLHttpRequest()
  xhr.open(method, url)//1
  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        success(xhr)//2
      } else if (xhr.status >= 400) {
        fail(xhr)//3
      }
    }
  }
  xhr.send(body)
  return {
    /* api */
  }
}

//使用AJAX
//未使用对象传参前
const successFn = () => {
  console.log('成功了')
}
const failFn = () => {
  console.log('失败了')
}
ajax('get', '/data', undefined, successFn, failFn)

//使用对象传参后
ajax({
  method: 'get',
  path: '/data',
  successFn: (xhr) => {
    console.log('成功了')
  },
  failFn: (xhr) => {
    console.log('成功了')
  }
})

AJAX的优缺点

优点

  • 可以请求任意内容(但是不能跨域)
  • 不用刷新页面

缺点

  • 代码难记
  • 不能跨域