XMLHttpRequest 重要的屬性: onreadystatechange,readyState,status, statusText ,responseXML ,responseText。
- onreadystatechange
參考至callback函式,readyState每次改變時,都會呼叫onreadystatechange所參考的函式。 - responseText
伺服器傳來的請求回應文字,會設定給這個屬性。 - responseXML
伺服器傳來的請求回應如果是XML,會成為DOM設定給這個屬性。 - statusText
返回當前 XMLHttpRequest 請求的回應行狀態,回傳值: string status - readyState
回應 XMLHttpRequest 的當前狀態,會有0到4的數值,共有5個狀態
0 = UNINITIALIZED; opennot yet called
(未初始化) Object已建立,但是尚未初始化(尚未使用open方法)
1 = Open; send for request not yet called
(初始化) Object已建立,尚未使用send方法
2 = Sent; send called, headers and status are available
(送出數據) send方法已使用,但是當前的狀態及http檔頭頭未知
3 = Receiving; downloading response, responseText only partially set
(數據傳送中) 已接收部分數據,因為回應及http檔頭不全,這時通過 responseBody 和responseText 獲取部分數據會出現錯誤
4 = COMPLETED; finished downloading
(完成)數據接數完畢,此時可以通過 responseBody 和 responseText 獲取完整的回應數據
• status: 回應 XMLHttpRequest 請求的 http 狀態碼 ,回傳值:integer status code
100:Continue
101:Switching protocols
200:OK
201:Created
202:Accepted
203:Non-Authoritative Information
204:No Content
205:Reset Content
206:Partial Content
300:Multiple Choices
301:Moved Permanently
302:Found
303:See Other
304:Not Modified
305:Use Proxy
307:Temporary Redirect
400:Bad Request
401:Unauthorized
402:Payment Required
403:Forbidden
404:Not Found
405:Method Not Allowed
406:Not Acceptable
407:Proxy Authentication Required
408:Request Timeout
409:Conflict
410:Gone
411:Length Required
412:Precondition Failed
413:Request Entity Too Large
414:Request-URI Too Long
415:Unsupported Media Type
416:Requested Range Not Suitable
417:Expectation Failed
500:Internal Server Error
501:Not Implemented
502:Bad Gateway
503:Service Unavailable
504:Gateway Timeout
505:HTTP Version Not Supported
PS:此屬性 status 是唯讀,返回當前 XMLHttpRequest 請求的 http 狀態碼 ,此屬性僅當數據送出並完整接收完畢後才可以獲取。
程式範例如下:
if(myXmlHttp.readyState == 4) {
if(myXmlHttp.status == 200) {
//以純文字方式取回伺服器回傳資料
txtresp = myXmlHttp.responseText;
//以 XML 方式取回伺服器回傳資料
xmlresp = myXmlHttp.responseXML;
if (txtresp) {
alert(txtresp);
document.getElementById("myTxtResp").innerHTML = txtresp;
}
}
}