使用 JavaScript 封装一个优秀的 AJAX 方法!

43 min read

可以像这样封装一个ajax方法:

function ajax(options){
  var xhr = new XMLHttpRequest();
  
  // 处理参数
  options.type = options.type.toUpperCase() || 'GET';
  options.dataType = options.dataType.toUpperCase() || 'JSON';
  
  // 处理data参数
  var params = [];
  for(var key in options.data){
    params.push(key + '=' + options.data[key]);
  }
  var postData = params.join('&');

  // 处理GET请求,添加参数到URL中
  if(options.type === 'GET'){
    options.url += '?' + postData;
  }

  xhr.open(options.type, options.url, true);

  // 处理header参数
  if(options.headers){
    for(var key in options.headers){
      xhr.setRequestHeader(key, options.headers[key]);
    }
  }

  xhr.onreadystatechange = function(){
    if(xhr.readyState === 4){
      var status = xhr.status;
      if(status >= 200 && status < 300){
        var response = options.dataType === 'JSON' ? JSON.parse(xhr.responseText) : xhr.responseText;
        options.success && options.success(response);
      }else{
        options.error && options.error(status);
      }
    }
  };
  
  // 处理POST请求,发送数据
  if(options.type === 'POST'){
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(postData);
  }else{
    xhr.send();
  }
}

使用方法:

ajax({
  url: 'http://example.com/api/users',
  type: 'GET',
  data: {
    name: 'John',
    age: 30
  },
  headers: {
    token: 'a1b2c3d4e5f6'
  },
  success: function(response){
    console.log(response);
  },
  error: function(status){
    console.log('Error: ' + status);
  }
});