原生JS封装ajax请求

316 阅读1分钟

贴代码:

两个工具函数,下面会用到

// 处理请求参数
const formatParams = data => {
  var arr=[];
  for(var name in data){
    arr.push(encodeURIComponent(name)+"="+encodeURIComponent(data[name]));
  }
  return arr.join("&");
}

// 处理用户传入的 headers
const handleRequestHeader = (headers, xhr) => {
  for(let k in headers) {
    xhr.setRequestHeader(k, headers[k]);
  }
} 

抽取公共的 XMLHttpRequest 实例代码

const requestInstance = callback => {
  return new Promise((resolve, reject) => {
    var xhr = null
    if(window.XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    }else if(window.ActiveObject) {     // 兼容IE6以下版本
      xhr = new ActiveObject("Microsoft.XMLHTTP")
    }
    // 针对 get/post 等不同请求,实现各自对应的xhr.open()/xhr.send()
    callback(xhr)
    
    // 请求超时处理
    setTimeout(() => {
      if(xhr.readySate !== 4) reject("请求超时")
    }, 10000)
      
    xhr.onreadystatechange = () => {
      if(xhr.readyState === 4) {
        var status = xhr.status;
        if(status >= 200 && status < 300 || status === 304){
          resolve(xhr.responseText, xhr.responseXML)
        }else{
          reject(status)
        }
      }
    }
  })
}

封装 get / post / put / delete 请求

const get = (url, data, headers = {}) => {
  return requestInstance(xhr => {
    let params = "?" + formatParams(data)
    xhr.open("get", url + params, true);
    handleRequestHeader(headers, xhr)
    xhr.send(null);
  })
}

const post = (url, data, headers = { "Content-type": "application/x-www-form-urlencoded" }) => {
  return requestInstance(xhr => {
    let params = formatParams(data)
    xhr.open("post", url, true);
    handleRequestHeader(headers, xhr)
    xhr.send(params);
  })
}


const put = (url, data, headers = { "Content-type": "application/x-www-form-urlencoded" }) => {
  return requestInstance(xhr => {
    let params = formatParams(data)
    xhr.open("put", url, true);
    handleRequestHeader(headers, xhr)
    xhr.send(params);
  })
}

// 变/常量不能命名为 delete,所以这里命名为大写的 DELETE
const DELETE = (url, data, headers = {}) => {
  return requestInstance(xhr => {
    let params = "?" + formatParams(data)
    xhr.open("delete", url + params, true);
    handleRequestHeader(headers, xhr)
    xhr.send(null);		
    // 有时候delete请求传参,参数需要放到请求体里,这里改为:xhr.send(data)。封装时需要与后端约定好delete的传参方式	
  })
}

整合到ajax对象中

const ajax = {
  get,
  post,
  put,
  delete: DELETE
}

html中引用

<script src="./ajax.js"></script>
<script>
    window.onload = () => {
        ajax.post("http://localhost:8080/api/login", {
          username: "tom",
          password: "123456"
        }).then((data) => {
          console.log(data)
        })
    }
</script>

以post请求为例:

参考链接:www.cnblogs.com/qing-5/p/11…