1. 程式人生 > >封裝ajax請求函式

封裝ajax請求函式

//封裝適合各種情況的簡化版ajax函式
function ajax({//利用解構,獲取將來引數物件中每個屬性值
  type,//請求型別: "get"||"post"
  url,//請求的url地址: "xxx.php"
  data,//請求攜帶的引數: "變數1=值&..."
  dataType,//伺服器端返回值型別: "json"||"text"
}){
  //只要遠端請求,必有延遲,只要延遲,比用promise等待完成後,才執行後續操作
  return new Promise(callback=>{//.then()
    //AJAX 4步/5步:
    var xhr=new XMLHttpRequest();//1.獲得xhr物件
    //如果是get請求,且傳入了data引數,才需要拼接url和data為get請求的完整地址
    if(type.toLowerCase()=="get"&&data!==undefined)
      url+="?"+data;
    xhr.open(type,url,true);//2. 建立連線
    //3. 設定請求狀態回撥函式
    xhr.onreadystatechange=function(){
      //如果請求完成,且成功!
      if(xhr.readyState==4){
				if(xhr.status==200){
					var resData=xhr.responseText;
					//如果伺服器端響應型別不是json,則呼叫後續resolve操作,並傳入原始responseText,做後續處理
					if(dataType!==undefined
						&&dataType.toLowerCase()=="json")
						resData=JSON.parse(resData);
					callback(resData);
				}
      }
    }
    //只有type為post,才需要設定請求頭
    if(type.toLowerCase()=="post")
      xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    //只有type為post,才需要send時,傳入引數
    xhr.send(type.toLowerCase()=="post"?data:null);
  })
}