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 ,默認是 textresponse
響應內容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 以後,響應超時時觸發
xhr.upload 是 ajax 上傳對象
xhr.upload 也有如下事件progress
load
error
abort
xhr.upload.onprogress 和 xhr.onprogress 使用差很少,只是一個針對文件上傳過程,一個針對從服務器獲取響應的過程
表單數據類型
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();