一、XMLHttpResquest 簡介html
XMLHttpRequest是一個API,用於客戶端和服務器之間傳輸數據,通 過URL獲取數據簡單,且不會刷新整個頁面,用戶發起請求後可作其餘事情,不用一直等到服務器響應,具備很好的用戶體驗而被普遍應用。ajax
二、屬性和方法json
onreadystatechange瀏覽器
是function類型,綁定一個函數,當請求狀態(readyState)改變時,就會調用它。注意,只能在異步請求中使用。安全
readyState,一個無符號整數,表示請求狀態。服務器
0——UNSENT(未打開),建立了xhr對象,open()還沒調用。app
1——opened(未發送),調用了open()可是還沒調用send()。
2——HEADERS_RECEIVED(已接收響應頭信息),send()被調用,響應頭和響應狀態已返回。
3——LOADING(下載響應中),響應體下載中,已經從responseText中得到部分數據。
4——DONE(請求完成),整個請求完成,不是表明請求成功了,請求失敗也算完成。異步
response: async
只讀屬性,返回接收到的數據主體,類型但是ArrayBuffer(內存緩衝區?不太理解)、Bold(不太理解)、Documnet(HTML文本或片斷、XML)、JSON(JS對象)、text(字符串),由responseType決定。請求失敗或者數據不完整,該屬性只爲null。ide
" "——字符串,默認值。
"document"——Document對象即XML、html文檔或html片斷。
"json"——JSON對象。
"text"——字符串。
"blod"——Bold對象(不是很明白??)
var xhr= new XMLHttpResquest(); xhr.open("GET",URL,true); xhr.responseType="json";
responseType 設置爲 json,支持json的瀏覽器,主流瀏覽器都支持,會自動調用JSON.parese()方法,將JSON解析爲JS對象,就是說 從xhr.response(不是xhr.responseText屬性)屬性獲得的不是文本,是JS對象。
responseText,
返回的字符串,只讀,請求不成功或者數據不完整,該屬性爲null。若是返回的是JSON格式的數據,就能夠調用responseText屬性。
1 var data = xhr.responseText; 2 data=JSON.parse(data);//解析JSON爲JS對象。
status,
只讀屬性,HTTP狀態碼,是一個三位數的整數。
200,ok,響應成功。
301,Moved Permanently,永久移動。
302, Move temporarily,暫時移動
304, Not Modified,未修改
307, Temporary Redirect,暫時重定向
401, Unauthorized,未受權
403, Forbidden,禁止訪問
404, Not Found,未發現請求資源
500, Internal Server Error,服務器發生錯誤
只有 2xx和304表示服務器正常。
1 if (ajax.readyState == 4) { 2 if ( (ajax.status >= 200 && ajax.status < 300) 3 || (ajax.status == 304) ) { 4 // Handle the response. 5 } else { 6 // Status error! 7 } 8 }
statusText,只讀屬性,一個字符串,表示服務器的狀態,是一個完整信息,如 「200 OK」。
1 var xhr = new XMLHttpRequest(); 2 xhr.ontimeout = function () { //timeout 是 xhr 的一個事件,超時時觸發 3 console.error("The request for " + url + " timed out."); 4 }; 5 xhr.onload = function() { //load 是 xhr 的一個事件,表示加載 6 if (xhr.readyState === 4) { 7 if (xhr.status === 200) { 8 callback.apply(xhr, args); 9 } else { 10 console.error(xhr.statusText); 11 } 12 } 13 }; 14 xhr.open("GET", url, true);//初始化一個請求 15 xhr.timeout = timeout; //設置超時 16 xhr.send(null); //發送請求 17 }
方法:
abort()——請求發送後,調用該方法中斷,在send()以後調用,不然報錯。
getAllReponseHeaders()——獲取所有響應頭信息,響應還沒接收,返回null。
getResponseHeader(DOMString header)——返回指定的頭信息,不接受或者不存在,返回null。
open(method,url,[async,uers,password])——初始一個請求,該方法用在js中,本地openRequest()。
參數:
method:HTTP方法:GET|POST|PUT|DELETE。不是HTTP(S)的協議,忽略該參數。保持大寫,不然有些瀏覽 器不識別。
url:請求服務器的頁面。出於安全考慮,必須是相同域名下的頁面。
async:布爾值,表示是否採用異步請求,可選。true爲默認值,表示異步。
uesr:用戶名,可選。
password:密碼,可選。
overrideMimeType(),
重寫服務器返回的MIME type。如強制將響應流當成"text/html"來處理和解析。必須在sned()以前調用。
這個比較麻煩,通常用 responseType屬性設置。
1 var xhr = new XMLHttpRequest(); 2 xhr.onload = function(e) { 3 var arraybuffer = xhr.response; 4 // ... 5 } 6 xhr.open("GET", url); 7 xhr.responseType = "arraybuffer"; 8 xhr.send();
send(): 發送請求,異步請求,當即返回,同步請求,直到響應徹底接收後返回。全部相關的事件綁定必須在調用send()方法以前進行.
在POST方法中,向服務器提交的表單數據傳入send()中,序列化和轉碼處理,名值對用&鏈接,如 "name=jack&age=20",且在send()調用前,須要設置MIME類型:
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
GET請求中不用參數。send()或者send(null)
setRequestHeader(),設置HTTP請求頭的信息,必須在open()以後和send()以前。
事件:
loadstart:請求開始,loadstart事件被觸發。
屬性:
arget:事件目標。
type:事件類型。
loaded:大於零的數,表示已經加載的資源的字節數。
total:加載資源的總數。
用於 xhr請求 <img>、<video>。
progress:請求進度。
error:請求出錯時觸發。
abort:請求中斷而不是由於錯誤,經常是用戶取消。
load:資源下載完成。
loadend:下載結束,當再也不加載資源是觸發,如何出現 error、abort,load。
timeout:加載超時。
上傳文件時,XMLHTTPRequest對象的upload屬性有一個progress,會不斷返回上傳的進度。
1 <progress min="0" max="100" value="0">0% complete</progress>
1 function upload(blobOrFile) {//定義上傳文件函數 2 var xhr = new XMLHttpRequest(); 3 xhr.open('POST', '/server', true); 4 xhr.onload = function(e) { ... }; 5 6 // Listen to the upload progress. 7 var progressBar = document.querySelector('progress'); 8 xhr.upload.onprogress = function(e) { 9 if (e.lengthComputable) { //lengthComputable 是 progress 的一個屬性,表示資源是否可計算字節流 10 progressBar.value = (e.loaded / e.total) * 100; 11 progressBar.textContent = progressBar.value; //有點瀏覽器不支持,這是後備選擇 12 } 13 }; 14 15 xhr.send(blobOrFile); 16 } 17 18 upload(new Blob(['hello world'], {type: 'text/plain'}));
1 xhr.addEventListener("progress", updateProgress); 2 xhr.addEventListener("load", transferComplete); 3 xhr.addEventListener("error", transferFailed); 4 xhr.addEventListener("abort", transferCanceled); 5 6 xhr.open(); 7 8 function updateProgress (oEvent) { 9 if (oEvent.lengthComputable) { //可計算數據總量 10 var percentComplete = oEvent.loaded / oEvent.total; 11 // ... 12 } else { 13 // 迴應的總數據量未知,致使沒法計算百分比 14 } 15 } 16 17 function transferComplete(evt) { 18 console.log("The transfer is complete."); 19 } 20 21 function transferFailed(evt) { 22 console.log("An error occurred while transferring the file."); 23 } 24 25 function transferCanceled(evt) { 26 console.log("The transfer has been canceled by the user."); 27 }
今天就學到這裏了,在第二篇中寫一個發起請求函數。仍是不太熟悉博客園的後臺,用的很不習慣。