【JavaScript】自己动手封装一个ajax函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AC_greener/article/details/88233479

我们在jquery中一般是这样是用ajax函数的:

xxx.addEventListener('click', function(){
  window.ajax({
    url:'/xxx',
    method: 'get',
    body: '',    //请求体,method为get可以为空
    headers: {   //请求头
      'content-type': 'application/x-www-form-urlencoded'
    }, 
    successFn: function() {
      console.log(success)
    },
    failFn: function() {
      console.log(fail)
    }
  })
})

基于上面的代码我们封装一个window.ajax函数

window.ajax = function(options) {
  let {url, method, body, headers, successFn, failFn} = options
  let xhr = new XMLHttpRequest()
  xhr.open(method, url)
  
  for(key in headers) {
    let value = headers[key]
    xhr.setRequestHeader(key, value)
  }

  xhr.onreadystatechange = function() {
    if(xhr.readyState === 4) {
      if(xhr.status >= 200 && xhr.status < 300) {
        successFn.call(undefined, xhr.responseText)
      } else if(xhr.status >= 400) {
        failFn()
      }
    }
  }
  xhr.send(body)
}

猜你喜欢

转载自blog.csdn.net/AC_greener/article/details/88233479