如何創建ajax

如何創建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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章