AJAX應用的五個步驟
1.建立xmlHttpRequest對象
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
if(xmlHttp.overrideMimeType) {
xmlHttp.overrideMimeType("text/xml");
}
} else if(window.ActiveXobject) {
var activeName = ["MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
for(var i = 0; i < activeName.length; i++) {
try {
xmlHttp = new ActiveXobject(activeName[i]);
break;
} catch(e) {}
}
}
if(!xmlHttp) {
alert("創建xmlhttprequest對象失敗");
} else {}
2.設置回調函數
xmlHttp.onreadystatechange= callback;
function callback(){}
3.使用OPEN方法與服務器建立連接 xmlHttp.open("get","ajax?name="+ name,true)
此步註意設置http的請求方式(post/get),如果是POST方式,註意設置請求頭信息xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
4.向服務器端發送數據
xmlHttp.send(null);
如果是POST方式就不為空
5.在回調函數中針對不同的響應狀態進行處理
if(xmlHttp.readyState == 4){ //判斷交互是否成功
if(xmlHttp.status == 200){ //獲取服務器返回的數據 //獲取純文本數據
var responseText =xmlHttp.responseText;
document.getElementById("info").innerHTML = responseText;
}
}
AJAX應用的五個步驟