當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
javascript --- XMLHttp2级、CORS(跨域资源共享)
生活随笔
收集整理的這篇文章主要介紹了
javascript --- XMLHttp2级、CORS(跨域资源共享)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
FormData:
// 為序列化表單以及創(chuàng)建與表單格式相同的數(shù)據(jù)提供了便利 var data = new FromData(); data.append("name", "Nicholas");// 使用FormData標(biāo)準(zhǔn)化數(shù)據(jù)后,發(fā)送到服務(wù)器 var xhr = createXHR(); xhr.onreadystatechange = function () {if ( xhr.readyState ==4){if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {alert(xhr.responseText);} else {alert("Request was unsuccessful: " + xhr.status);}} }; xhr.open("post", "postexample.pht", ture); var form = document.getIEmentById("user-info"); xhr.send(new FormData(form));超時設(shè)定:
// 僅適用于IE8 var xhr = createXHR(); xhr.onreadystatechange = function() {if( xhr.readyState == 4) {try {if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {alert(xhr.responseText);} else {alert("Request was unsuccessful: " + xhr.status);}} catch (ex) {// 假設(shè)由 ontimeout 事件處理程序處理}} }; xhr.open("get", "timeout.php", true); xhr.timeout = 1* 1000; // 超時設(shè)置為1秒 xhr.ontimeout = function () {alert("Request did not return in a second."); }; xhr.send(null);ouverrideMimeType方法:
// 用于重寫XHR響應(yīng)的MIME類型 var xhr = createXHR(); xhr.open("get", "text.php", true); xhr.overriderMimeType("text/xml"); xhr.send(null);// 注:若服務(wù)器返回的MIME類型是text/plain,通過overrideMimeType重寫為 text/xml 類型,便于處理進(jìn)度事件:
// loadstart: 在接收到相應(yīng)數(shù)據(jù)的第一個字節(jié)時觸發(fā) // progress: 在接收響應(yīng)期間持續(xù)不斷地觸發(fā) // error: 在請求發(fā)生錯誤時觸發(fā) // abort:在因?yàn)檎{(diào)用abort()方法而終止連接時觸發(fā) // load: 在接收到完整的響應(yīng)數(shù)據(jù)時觸發(fā) // loadend: 在通信完成或者觸發(fā)error、abort或load事件后觸發(fā)// load事件 var xhr = creatXHR(); xhr.onload = function() {if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {alert(xhr.responseText);} else {alert("Request was unsuccessful: " + xhr.stauts);} }; xhr.open("get", "altevents.php", true); xhr.send(null);// progress事件 var xhr = createXHR(); xhr.onload = function(event) {if ((xhr.status >=200 && xhr.status < 300) || xhr.status == 304) {alert(xhr.responseText);} else {alert("Request was unsuccessful: " + xhr.status); }; xhr.onprogress = function(event) {var divStatus = document.getElementById("status");if ( event.lengthComputable) {divStatus.innerHTML = "Received " + event.position + " of" + event.totalSize + " bytes" ;} }; xhr.open("get", "altevents.php" , true); xhr.send(null);// 注1:onprogress事件會在瀏覽器接收新數(shù)據(jù)期間周期性地觸發(fā),其事件處理程序會接收到一個event對象 // 注2:event對象有3個屬性: // lengthComputable:表示進(jìn)度信息是否可用的布爾值 // postion:已經(jīng)接收到的字節(jié)數(shù) // totalSize:根據(jù)Content-Length響應(yīng)頭部確定的預(yù)期字節(jié)數(shù)跨域資源共享: (Cross-Origin Resource Sharing,CORS)是W3C的一個工作草案,定義了在 必須訪問跨域資源時,瀏覽器與服務(wù)器應(yīng)該如何溝通.
// 首先要明確簡單請求的概念,滿足以下條件: // (1)請求方法是HEAD、GET、POST之一 // (2)HTTP頭部不超過以下幾種字段: // ·Accept:告訴服務(wù)器能夠發(fā)送哪些媒體類型 // ·Accept-Language:告訴服務(wù)器能夠發(fā)送哪些語言 // ·Content-Language:理解主體時最適宜使用的自然語言 // ·Last-Event-ID: ...未找到 // ·Content-Type:(只限于application/x-www-form-unlencoded、multipart/form-data、text/plain)// 對于簡單請求,在頭信息中,增加一個Origin字段 GET /cors HTTP/1.1 Origin: http://api.bob.com // 用于說明本次請求來自哪個源(協(xié)議 + 域名 + 端口) Host: api.alice.com Accept-Language: en-US Connection: keep-alive User-Agent: Mozilla/5.0 ...// 如果Origin指定的源,不在許可范圍內(nèi),服務(wù)器會返回一個正常(注意是正常的)的HTTP. // 當(dāng)瀏覽器發(fā)現(xiàn)響應(yīng)報(bào)文中沒有Access-Control-Allow-Origin字段.就知道請求出錯了,從而調(diào)用xhr.onerror事件處理函數(shù) // 如果Origin指定的源的域名在許可范圍內(nèi),服務(wù)器返回響應(yīng),響應(yīng)首部多出幾個字段如下: Access-Control-Allow-Origin: http://api.bob.com // 表示接收該域源的請求 Access-Control-Allow-Credentials: true // 表示是否允許發(fā)送Cookie Access-Control-Expose-Headers: FooBar Content-Type: text/html; charset = utf-8IE對CORS的實(shí)現(xiàn): 微軟在IE8中引入了XDR類型,用于實(shí)現(xiàn)安全可靠建的跨域通信
var xdr = new XDomainRequest(); xdr.onload = function () {alert(xdr.responseText); }; xdr.onerror = function () {alert("An error occurred."); } xdr.open("get", "http://www.somewhere-else.com/page/"); xdr.send(null);// 注:通過xdr方法請求的數(shù)據(jù),沒有響應(yīng)碼,只有error事件.// xdr的contentType屬性,用來表示發(fā)送數(shù)據(jù)的格式 var xdr = new XDomainRequest(); xdr.onload = function() {alert(xdr.responseText); }; xdr.onerror = function () {alert("An error occurred."); }; xdr.open("post", "http://www.somewhere-else.com/page/"); xdr.contentType = "applicatin/x-www.form-urlencoded"; xdr.send("name1=value1&name2=value2");其他瀏覽器對CORS的實(shí)現(xiàn):
// 使用原生的XHR對象,在傳入url的時候,傳入絕對URL即可. var xhr = createXHR(); xhr.onreadystatechange = function() {if (xhr.readyState == 4) {if ((xhr.status >=200 && xhr.status < 300) || xhr.status == 304) {alert(xhr.responseText);} else {alert("Request was unsuccessful: " + xhr.status);}} }; xhr.open("get", "http://www.somewhere-else.com/page/", true); xhr.send(null);跨瀏覽器的CORS:
// 檢測XHR是否支持CORS的最簡單方式,就是檢查是否存在withCredentials屬性.再結(jié)合檢測XDomainRequest對象是否存在,即可實(shí)現(xiàn)兼容. function createCORSRequest (method, url) {var xhr = new XMLHttpRequest();if ("withCredentials" in xhr) {xhr.open(method, url, true);} else if ( typeof XDomainRequest != "undefined") {xhr = new XDomainRequest();xhr.open(method, url);} else {xhr = null;}return xhr; } var request = createCORSRequest("get", "http://www.somewhere-else.com/page/"); if(request) {request.onload = function () {// 對 request.responseText 進(jìn)行處理};request.send(); }參考《JavaScript高級程序設(shè)計(jì)》(第3版)P578~P586
參考 阮一峰-跨域資源CORS詳解
參考 《HTTP權(quán)威指南》P73、 P76
總結(jié)
以上是生活随笔為你收集整理的javascript --- XMLHttp2级、CORS(跨域资源共享)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab将数据输出到excel中,m
- 下一篇: javascript --- 几个其他