function ajax(){
var xhr = null;
//實(shí)例化XMLHttpRequest對象
if(window.ActiveXObject){//ie5髓窜、ie6
xhr = new Active XObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
//通過open方法初始化XMLHttpRequest對象,指定請求的method蹭秋、url、async參數(shù)虑啤,true表示異步加載(默認(rèn))作媚,false為同步
xhr.open("GET","test.php",true);
//注冊回調(diào)事件處理器,當(dāng)XMLHttpRequest.readuyState發(fā)生變化時庭猩,激發(fā)readystatechange事件窟她,從而調(diào)用這里注冊的處理器ajaxCallBack
xhr.onreadystatechange = ajaxCallBack;
//發(fā)送請求
//GET請求
xhr.send(null);
//POST請求,添加請求的HTTP頭
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
//POST請求,參數(shù)為發(fā)送給服務(wù)器的請求數(shù)據(jù)
xhr.send('String');
}
function ajaxCallBack(){
if(xhr.readyState == 4){//請求完成加載
if(xhr.status == 200){//響應(yīng)已經(jīng)成功
console.log(xhr.responseText);//打印響應(yīng)內(nèi)容
//在實(shí)際開發(fā)中蔼水,這里的響應(yīng)內(nèi)容一般為JSON格式數(shù)據(jù)震糖,所以我們要先將JSON數(shù)據(jù)進(jìn)行解析
var res = xhr.responseText;
var data = JSON.parse(res);
if(data.status == 0){
//進(jìn)行數(shù)據(jù)操作
}
else{
//打印后臺給的錯誤信息
console.log(data.info);
}
}
}
}
`