AJAX

/**
 * ajax 封装
 * @param {obj{url,type,data,success,error}} obj
 */
function ajax (obj) {
  obj = obj || {};
  obj.url = obj.url || '';
  obj.type = (obj.type || 'GET').toUpperCase();
  let params = formatParams(obj.data);
  let xhr = null;

  // 兼容性
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
  }

  // 发送请求
  if (obj.type === 'GET') {
    xhr.open(obj.type, obj.url + '?' + params, true);
    xhr.send(null);
  } else if (obj.type === 'POST') {
    xhr.open(obj.type, obj.url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(params);
  }

  // 响应
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
        obj.success && obj.success(xhr.responseText);
      } else {
        obj.error && obj.error(xhr);
      }
    }
  }
  // 格式化请求参数
  function formatParams (data) {
    let arr = [];
    for (let i in obj) {
      arr.push(i + '=' + obj[i]);
    }
    return arr.join('&');
  }
}
// 使用
ajax({
  url: '',
  type: 'GET',
  data: {
    user: 'user',
    password: 'password'
  },
  success: function (data) {
    console.log(data)
  },
  error: function (e) {
    console.log(e);
  }
});

你可能感兴趣的:(AJAX)