原生js使用XMLHTTPRequest对象实现ajax函数封装

XMLHTTPRequest对象实现ajax函数封装

function ajax (options) {
  var defaults = {
    type: 'get',
    url: '',
    data: {},
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function () {},
    error: function () {}
  };
  // 用options对象中的属性覆盖defaults对象中的属性,原位操作
  Object.assign(defaults, options);

  var xhr = new XMLHttpRequest();
  var params = '';
  for( var attr in defaults.data){
    params += attr + "=" + defaults.data[attr] + "&";
  }
  params = params.substr(0, params.length - 1);
  if(defaults.type == 'get') {
    defaults.url += "?" + params;
  }
  xhr.open(defaults.type, defaults.url);
  if(defaults.type == 'get') {
    xhr.send();
  }else {
    var contentType = defaults.header['Content-Type'];
    // 如果请求类型为post,必须明确设置报文头的类型
    xhr.setRequestHeader('Content-Type', contentType);
    if(contentType == 'application/json') {
      xhr.send(JSON.stringify(defaults.data));
    }else{
      xhr.send(params);
    }
  }
  xhr.onload = function () {
    if(xhr.status == 200){
      var resHeader = xhr.getResponseHeader('Content-Type');
      var responseText = xhr.responseText;
      if(resHeader.includes('application/json')) {
        responseText = JSON.parse(responseText);
      }
      defaults.success(responseText, xhr);
    }else {
      defaults.error(xhr.responseText, xhr);
    }
  };
  xhr.onerror = function () {
    defaults.error(xhr.responseText);
  };
}

调用的时候,给ajax函数传一个对象,不写的属性会采取默认值,其中:

  • type属性默认值是:‘get’
  • url属性默认值是: ‘’
  • data属性默认值是:{}
  • header属性默认值是: {
    ‘Content-Type’: ‘application/x-www-form-urlencoded’
    }
  • success: function () {}
  • error: function () {}

例如:

ajax({
  type: 'post',
  url: 'http://localhost/responseData',
  data: {
  	name: 'yibo'
  },
  success: function (res, xhr) {
    console.log(res, xhr);
  }
})

猜你喜欢

转载自blog.csdn.net/jal517486222/article/details/104753728