封裝ajax函數(shù)

/*
*封裝ajax函數(shù)
* @param options
*    options = {
*        type : "get|post", // 請(qǐng)求方式,默認(rèn)為 get
*        url : "", // 請(qǐng)求服務(wù)器資源url
*        data : {username:"xxx", password:""}, // 向服務(wù)器傳遞的數(shù)據(jù)
*        dataType : "text|json", // 預(yù)期從服務(wù)器返回?cái)?shù)據(jù)的格式
*        success : function(responseData){}, // 請(qǐng)求成功時(shí)執(zhí)行的函數(shù)
*        error : function(err){} // 請(qǐng)求失敗時(shí)執(zhí)行的函數(shù)
*    }
*/
function ajax(options){
  options = options || {};
  var method = (options.type || GET).toUpperCase(),
      url = options.url,
      queryString = null;
  if(!url)
    return;
  if(options.data){
    queryString = [];
    for(var attr in options.data){
      queryString.push(attr + "=" +options.data[attr]);
    }
    queryString = queryString.join("&");
  }
  if(method === "GET"){
    url += "?"+queryString;
    queryString = "";
  }
  var xhr = new XMLHttpRequest();
  xhr.open(method,url,true);
  if(method === "POST")
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send(queryString);
  xhr.onreadystatechange = function(){
    if(xhr.readyState === 4){
      if(xhr.status === 200){
        var data = xhr.responseText;
        if(options.dataType === "json")
          data = JSON.parse(data);
        options.success && options.success(data);
      }else{
        options.error && options.error(xhr.status);
      }
    }
  }
}


歡迎關(guān)注微信公眾號(hào):猴哥說前端