xhr2於xhr最大的區別在於xhr只支持字符串類型的數據,而xhr2支持任意類型的數據。使用XHR2向服務器請求一張圖片。跨域
1 <script> 2 var xhr=new XMLHttpRequest(); 3 xhr.open('get','image.jpg',true); 4 //處理返回類容的類型 5 xhr.responseType='blob'; 6 xhr.onload=function(e){ 7 if(this.status==200){ 8 var url=window.URL.createObjectURL(this.response); 9 var img=new image(); 10 img.src=url; 11 document.body.appendChild(img); 12 } 13 } 14 xhr.send(); 15 </script>
ArrayBuffer服務器
ArrayBuffer是一種數據類型,存放原始的固定長度的二進制數據,但ArrayBuffer沒法操做它的類容,必須建立一個表明固定格式的ArrayBufferView來 讀取具體的二進制數據。 實例cookie
var buffer=new ArrayBuffer(16);app
var int32View=new Int32Array(buffer);post
同一塊內存buffer能夠被多個視圖所超控。this
FormDataurl
XHR2的新類型,使用FormData提交表單spa
1:常見的提交表單 var formdata=new FormData(); formdata.append('username','frienr'); var xhr=new XMLHttpRequest(); xhr.open('post','/server',true); xhr.send(formdata); 2:直接提交表單元素 function sendForm(form){ var formData=new FormData(form); //在以知的表單後添加 formdata.append('token','1233'); xhr.send(formdata); } sendForm(document.getElementById('form1'));
xhr2新增了個upload屬性,並能夠爲之綁定一個onprogress事件,檢測上傳的速度code
<progress></progress> <script> var xhr=new XMLHttpRequest(); xhr.open('POST','/SERVER',true); xhr.onload=function(){......} //配合HTML5的progress一塊兒使用 var progressBar=document.querySelector('progress'); xhr.upload.onprogress=function(e){ if(e.lengthComputable){ progressBar.value=(e.loaded/e.total)*100; } }; xhr.send(blobOrFile) } var int16Array=new Int16Array(16) var blob=new Blob([int16Array]) upload(blob); </script>
xhr不能跨越,但xhr2新增了跨源資源共享的能力在服務器設置一些標頭實現真正的跨域Ajax請求 能夠跨某個域的http標頭orm
Access-Control-Allow-Origin:http://example.com
能夠來自全部域的訪問
Access-Control-Allow-Origin:*
讓跨域的http請求帶上cookie等 Access-Control-Allow-Credentials:true
在客戶端發送請求時須要在發送請求前將xhr的對象withCredentials設置爲true eg xhr.withCredentials=true;