1. 程式人生 > >原生js的ajax請求簡單封裝

原生js的ajax請求簡單封裝

小總結: 

function ajax({url,type,data,dataType}){
	return new Promise(function(open,err){
		  //1. 建立xhr物件
		  var xhr=new XMLHttpRequest();
		  //2.繫結監聽事件
		  xhr.onreadystatechange=function(){
			  if(xhr.readyState==4&&xhr.status==200){
				  var res=xhr.responseText;
				  if(dataType==="json")
					  res=JSON.parse(res)
				  open(res);
			  }
		  }
		  if(type=="get"&&data!=undefined){
			  url+="?"+data;
		  }
		  //3.開啟連線
		  xhr.open(type,url,true);
		  if(type==="post")
			  //增加:設定請求訊息頭
			  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		  //4.傳送請求
		  if(type=="post"&&data!==undefined)
			  xhr.send(data);
		  else
			  xhr.send(null);
	})
  }