老鐵們往产,還記得如何對原生ajax進(jìn)行封裝嗎蝶防?注釋較少窄锅,看看是否還能看的明白偎箫?
封裝如下:
function ajax(obj){
//指定提交方式的默認(rèn)值
obj.type = obj.type || "get";
//設(shè)置是否異步木柬,默認(rèn)為true(異步)
obj.async = obj.async || true;
//設(shè)置數(shù)據(jù)的默認(rèn)值
obj.data = obj.data || null;
var params=_params(obj.data);
//在路徑后面添加時間戳加隨機數(shù)防止瀏覽器緩存。
obj.url+=(obj.url.indexOf("?")>-1?"&":"?")+"t="+((new Date()).getTime()+Math.random());
if(obj.type.toLowerCase()=="get" && params.length>0){//將轉(zhuǎn)換后的data.與url進(jìn)行拼接淹办。
obj.url+="&"+params;
}
var xhr=new XMLHttpRequest();
xhr.open(obj.type,obj.url,obj.async);
if(obj.type.toLowerCase()=="post"){
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(params)
}else
xhr.send(null);
if(obj.async){//異步調(diào)用
//監(jiān)聽響應(yīng)狀態(tài)眉枕。
xhr.onreadystatechange=function(){
if(xhr.readyState==4)//響應(yīng)狀態(tài)為4,數(shù)據(jù)加載完畢娇唯。
callback();
}
}else//同步
callback();
function callback(){
if(xhr.status==200){
obj.success(xhr.responseText);
}else{
obj.error(xhr.status);
}
}
//將對象序列化齐遵,將對象拼接成url字符串
function _params(data){
if(obj==null)
return obj;
var arr=[];
for(var i in data){
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
return arr.join("&");
}
}
調(diào)用如下:
ajax({
type:"get",
data:{
name:"laoliu"
},
url:"getUserByName.php",
async:false,
success:function(res){
//成功
},
error:function(error){
//失敗
}
})