ajax自己封装

2021-01-19 11:13

阅读:663

标签:result   hang   eof   number   use   status   XML   ESS   key   

function paramsSeralize(obj){
  if(!obj || typeof !== ‘object‘) return obj;
  let res = ‘‘;
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      res += `&${key}=${obj[key]}`
    }
  }
  result = result.substring(1);
  return result;
}
function ajax (options) {
  let params = Object.assign({
    method: ‘GET‘,
    url: ‘‘,
    data: null,
    params: null
  }, options)
  let isGet = /^(GET|OPTIONS|HEAD|DELETE)$/i.test(options.method)

  options.params ? options.params = paramsSeralize(options.params) : null;

  options.data ? options.data = paramsSeralize(options.data) : null;

  if(isGet && options.params){
    options.url += `${options.url.indexOf(‘?‘)>=0 ? ‘&‘ : ‘?‘}${options.params}`
  }

  let xhr = new XMLHttpRequest;
  xhr.open(options.method, options.url)

  !isGet ? xhr.setRequestHeader(‘Content-type‘,‘x-www-form-urlencoded‘) : null;

  xhr.onreadystatechange = function () {
    let { readyState, status, responseText } = xhr;
    if (/^2\d{2}/.test(status) && readyState === 4) {
      responseText = JSON.stringify(responseText)
      options.success && options.success()
    }
  }
  xhr.send(isGet ? null : options.data);
}

使用

 

ajax({
  method: ‘GET‘,
  url: ‘/user/list‘,
  data: {
    lx: 1,
    number: 2
  },
  params: {
    type: 1
  },
  success (res) {

  }
})

 

ajax自己封装

标签:result   hang   eof   number   use   status   XML   ESS   key   

原文地址:https://www.cnblogs.com/qqfontofweb/p/13336706.html


评论


亲,登录后才可以留言!