封装一个 ajax 函数,能实现如下方法调用

function ajax(options){
    //补全
}
ajax({
    url: 'http://api.jirengu.com/weather.php',
    data: {
        city: '北京'
    },
    onsuccess: function(ret){
        console.log(ret)
    },
    onerror: function(){
        console.log('服务器异常')
    }
})
function ajax(options){
  var url = options.url;
  var type = options.type || 'GET';
  var dataType = options.dataType || 'json';
  var onsuccess = options.onsuccess || function(){};
  var onerror = options.onerror || function(){};
  var data = options.data || {};
  
  var dataStr = [];
  for(var key in data){
    dataStr.push(key + '=' + data[key]);
  }
  dataStr = dataStr.jion('&');
  
  if(type === 'GET'){
    url += '?' + dataStr;
  }
  
  var xhr = new XMLHttpRequest();
  xhr.open(type, url, true);
  xhr.onload = function(){
    if((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304){
      // 成功了
      if(dataType === 'json'){
        onsuccess(Json.parse(xhr.responseText));
      }else{
        onsuccess(xhr.responseText);
      }
    }else{
      onerror();
    }
  };
  xhr.onerror = onerror;
  if(type === 'POST'){
    xhr.send(dataStr);
  }else{
    xhr.send();
  }
}

ajax({
  url: 'http://api.jirengu.com/weather.php',
  data: {
    city: '北京'
  },
  onsuccess: function(ret){
    console.log(ret);
  },
  onerror: function(){
    console.log('服务器异常');
  }
});

你可能感兴趣的:(封装一个 ajax 函数,能实现如下方法调用)