直接上代碼
// 使用xhr對(duì)象,判斷是否ie5/6
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
// ie56的使用的xhr對(duì)象
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
xhr.open('GET', 'url', true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState ===4 && xhr.status == 200 ){
console.log(xhr.responseText);
}
}
readyState存在的5個(gè)狀態(tài)
| 屬性 | 屬性含義 |
|---|---|
| 0(未初始化) | 對(duì)象已經(jīng)建立,請(qǐng)求未初始化,尚未調(diào)用open方法 |
| 1 初始化 | 對(duì)象已經(jīng)服務(wù)器連接已經(jīng)建立,尚未調(diào)用send方法 |
| 2 發(fā)送數(shù)據(jù) | send方法已調(diào)用,但是當(dāng)前的狀態(tài)及http頭未知 |
| 3 請(qǐng)求處理中 | 已接收部分?jǐn)?shù)據(jù),因?yàn)橄鄳?yīng)及http頭不全,這時(shí)通過(guò)responseBody和responseText獲取數(shù)據(jù)會(huì)出現(xiàn)錯(cuò)誤 |
| 4 請(qǐng)求已完成 | 數(shù)據(jù)接收完畢,此時(shí)可以通過(guò)responseBody和responseText獲取完整的回應(yīng)數(shù)據(jù)。 |
status狀態(tài)碼
200 ok