如何創建ajax
1 創建一個XMLHttpRequest對象(異步調用對象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest()
}else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
if (xhr==null) {
alert("Your browser does not support XMLHTTP.");
return;
}
2 設置onreadystatechange的回調函數
xhr.onstatechange = function(){
if(xhr.readyState === 4){
// readyState === 4 表示請求完成
if (xhr.status === 200)
// xhr.status === 200 表示相應成功
console.log(xhr.responseText)
}
}else {
// 響應失敗 根據響應碼判斷失敗原因
console.log(xhr.status)
}
}
3 創建一個新的http請求
xhr.open('get', 'test.asp')
// 第一個參數爲請求方法 get或post 第二個參數爲請求地址 第三個參數爲true代表異步請求(默認爲true,所以不用寫)
4 發送請求
xhr.send();