XMLHttpRequest level2

HTML5 更新了不少API,XMLHttpRequest 就是其中一個。level 2 的XMLHttpRequest 更增強大了。ajax

新建對象

var xhr = new XMLHttpRequst()
和以前同樣json

屬性

先看老幾樣屬性
onreadystatechange 同步ajax不可用此事件回調,abort() 也不會觸發此事件,open() 以前設置
readyState 只讀
responseText 只讀
responseXML
responseURL
status
statusText跨域

新屬性
responseType 設置響應類型,能夠是 arraybuffer / blob / document / json / text ,默認是 text
response 響應內容
timeout 超時毫秒數,同步請求不可用。默認是0,永不超時。在 open() 和 send() 之間設置,超時會觸發 xhr 的 timeout 事件
upload 只讀,ajax 上傳對象,後面詳細講
withCredentials Boolean,是否容許跨域響應設置cookie,默認是 false瀏覽器

方法

abort() 觸發 abort 事件服務器

getAllResponseHeaders() 返回全部響應頭部組成的字符串cookie

getResponseHeader(key)app

open(method, url)ide

overrideMimeType(mimetype) 重寫響應類型,若是須要的話,在 send() 以前調用url

send() 能夠發送 FormData / Blob / Buffer / String / Document,不發送數據的話,建議使用 xhr.send(null)code

setRequestHeader(key, value) 設置請求頭,在 open() 和 send() 之間調用。若是沒有設置 Accept, 則默認是 */*

事件

loadstart send() 以後觸發,只觸發一次
progress 進度事件,會不斷被觸發

xhr.addEventListener('progress', ev => {
  if (ev.lengthComputable) {
    console.log(ev.loaded / ev.total);
  }
});

ev.lengthComputable 長度可計算
ev.loaded 接收的字節數
ev.total 總字節數

// 可使用 'onprogress' in xhr 判斷瀏覽器是否支持 progress 事件

load 響應完成時觸發。使用此事件就不必再經過檢查 xhr.readyState === 4 來確認響應完成了。不過 load 事件只是表示接收到服務器的響應,還須要經過 xhr.status 來判斷響應是否成功。
error
abort xhr.abort() 觸發
timeout 設置 xhr.timeout 以後,響應超時時觸發

upload

xhr.upload 是 ajax 上傳對象
xhr.upload 也有如下事件
progress
load
error
abort
xhr.upload.onprogress 和 xhr.onprogress 使用差很少,只是一個針對文件上傳過程,一個針對從服務器獲取響應的過程

FormData

表單數據類型

var form = new FormData();
form.append('username', 'xiaoming');

或者
var form = new FormData(document.getElementsByTagName('form')[0]);

// 使用 FormData,不用設置請求的 Content-Type,xhr 可以自動識別並設置
// 若是不使用 FormData,發送表單須要先設置 Content-Type 爲 `application/x-www-form-urlencoded`, 若是表單中有文件須要上傳,則 Content-Type 爲 `multipart/form-data`
xhr.send(form);

// 若是隻是上傳文件,能夠直接使用 `xhr.send(file)`

綜上所述,使用 ajax 時,步驟以下:

  • var xhr = new XMLHttpRequest();

  • xhr.onreadystatechange = function () {}; level2 幾乎能夠不用了

  • xhr.open();

  • xhr 的相關設置,好比 事件監聽,請求頭設置,響應頭改寫等

  • xhr.send();

相關文章
相關標籤/搜索