XMLHttpRequest
- 創建:
var createXHR = function(){
var xhr = false;
try{
xhr = new XMLHttpRequest();//嘗試直接創建,適用于IE以外的大多數瀏覽器
}
catch(e){
try{
xhr = new ActiveXObject('Mxsm112.XMLHTTP');//嘗試使用較新版本IE的創建方式
}
catch(e){
try{
xhr = new ActiveXObject('Microsoft.XMLHTTP');//嘗試使用較老版本IE的創建方式
}
catch(e){
xhr = false;//創建失敗,返回false提示
console.log(e.name + ' : ' + e.message);
}
}
}
return xhr;
}
- 方法:
- open(method,url,async) :
- method指定請求使用的方法,包括GET、POST、HEAD、DELETE;
- url即請求地址;
- async規定是否啟用異步請求,異步請求將直接返回,需要使用事件監聽器在響應就緒后動態處理,默認為true;
- send() : 發送請求并根據同步異步設定適時返回,接受一個可選的請求體作為參數(在GET和HEAD中被忽略);
- abort() : 立即中斷已經發送的請求;對應請求的就緒狀態被置為0,但不會觸發readystatechange事件;
- onreadystatechange() : 當readyState發生變化時執行的事件處理函數;
- ontimeout() : 請求超時后調用的方法;
- 屬性:
- readyState:
- 0 請求未初始化,open()未調用;
- 1 請求已建立,未發送,send()尚未調用;
- 2 請求已發送,處理中,可以從響應中獲取首部(header)和狀態(status);
- 3 響應處理中,響應中已有部分數據可用,但未完全就緒;
- 4 響應已就緒;
- 注意,各瀏覽器中對就緒狀態的處理并不一致,不能過于依賴狀態來執行操作,測試在chrome(53)和Firefox(43)中onreadystatechange方法只能在狀態1和4時被調用,IE(11)則更奇特,依次出現了1、1、2、3、4的狀態,1出現了兩次。
- 無法通過onreadystatechange()僅在就緒狀態發生改變時被調用,但在readyState被在請求中斷(abort()被調用)被置0時不會觸發該方法,因而無法通過該方法獲取readyState為0的狀態,只能在請求未初始化或被中斷時手動獲取;
- upload:
- 返回一個代表上傳過程的對象,可以在其上注冊事件監聽器以追蹤上傳進程;
- 可選事件監聽器包括
- onloadstart : the fetch starts (請求開始裝載數據時調用的方法)
- onprogress : data transfer is going on (周期性調用的反饋上傳進度的方法)
- onabort : the fetch operation was aborted (請求中斷后調用的方法)
- onerror : the fetch failed (請求中出現錯誤時調用的方法)
- onload : the fetch succeeded (請求在抓取內容成功后返回時調用的方法)
- ontimeout : the fetch operation didn't complete by the timeout the author specified (請求超時調用的方法)
- onloadend : the fetch operation completed (either failed or succeeded)
- response:
- 返回相應的實體主體(response entity body),具體類型取決于responseType的值,在1.0中只有DOMString和 Document,在2.0中擴充了Blob、FormData、ArrayBuffer、File等;
- 當responseType為‘text’或空,response在請求處于loading狀態時保存部分響應文本(response text);
- responseType: 返回一個定義響應實體類型的枚舉值
- responseText: 返回一個包含響應文本(response as text)的DOMString,或者null;
- responseXML: 返回一個包含響應的Document,或者null(請求未發送,響應無法解析);
- status: 返回響應的狀態碼;
- statusText: 返回響應的狀態碼及服務器的反饋信息;
- timeout: 定義請求在被終結前可以維持的最大時長,以毫秒為單位;
- withCredentials: 一個布爾值,指示了Cross Site Access Control請求是否需要使用證書(如cookies,授權首部(authorization headers)或者TLS用戶證書等);該值的設定對同域請求沒有影響;
- In addition, this flag is also used to indicate when cookies are to be ignored in the response. The default is false. XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers.