1. 程式人生 > >AJAX——XMLHttpRequest物件主要屬性和事件

AJAX——XMLHttpRequest物件主要屬性和事件

 readyState屬性

有5個取值:0、1、2、3、4,表示HTTP請求的狀態和伺服器的響應。此屬性的值一般不會遞減,除非在正在進行的請求中呼叫了abort()或open()方法。理論上,每當這個屬性的值發生變化時都會觸發readyStateChange事件,但實際上,只有此屬性改變為4時才會觸發readyStateChange事件。

readyState值       

含義

     0

初始值,XMLHttpRequest物件剛剛建立時,或剛呼叫了abort()方法後

1

已經呼叫了open()方法,但還未呼叫send()方法,即還未傳送請求

2

已經呼叫了send()方法,也已經收到了響應頭,但還未收到響應主體

3

正在接收響應主體,但還未完成

4

HTTP響應已經全部接收完畢,或由於錯誤而停止

  responseText屬性

此屬性值為字串String

  • 當readyState<3,此屬性為空字串;
  • 當readyState=3,此屬性值為目前已經接收到的響應主體部分;
  • 當readyState=4,此屬性值為響應的全部主體

responseXML屬性

請求響應為有效的XML或HTML文件時,此屬性值為Document物件;當響應主體還沒有就緒,或不是有效的XML或HTML文件,此屬性值為null。

status屬性與statusText屬性

status屬性指伺服器返回的HTTP狀態碼,statusText屬性則指HTTP狀態碼對應的文字說明。


事件處理程式

onabort

當請求中止時觸發

onload

當請求成功時觸發

onloadend

在請求成功或者失敗時觸發;load、abort、error、timeout事件發生之後

onloadstart

當請求開始時觸發

onreadystatechange

當readyStateChange屬性改變時觸發

ontimeout

當timeout屬性指定的時間已經過去但響應依舊沒有完成時觸發

onerror

當請求因錯誤失敗時觸發。注意404等狀態碼不是error,因為此時響應仍然是成功完成的。

onprogress

當響應主體正在下載重複觸發(約每隔50ms一次)

————————————————————————————————————————————————————————————————————————————

以下是W3C官方標準的解釋:http://www.w3.org/TR/XMLHttpRequest/#events

The following are the event handlers (and their corresponding event handler event types) that must be supported on objects implementing an interface that inherits from as attributes:

The following is the event handler (and its corresponding event handler event type) that must be supported as attribute solely by the  object:


Event name Interface Dispatched when…
readystatechange Event The  attribute changes value, except when it changes to UNSENT.
loadstart The request starts.
progress Transmitting data.
abort The request has been aborted. For instance, by invoking the  method.
error The request has failed.
load The request has successfully completed.
timeout The author specified timeout has passed before the request completed.
loadend The request has completed (either in success or failure).