1. 程式人生 > 實用技巧 >ajax自己封裝

ajax自己封裝

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) {

  }
})