跨域通訊/跨域上傳淺析

來源:互聯網
上載者:User

標籤:http   io   os   ar   for   檔案   sp   資料   on   

web項目跨域問題主要包括跨域通訊和跨域上傳,下面對這兩方面分別做一個分析,具體項目中用哪個方案要看項目具體需求。

跨域通訊
  • jsonp
  • hash
  • server proxy
  • window.name
  • cors
  • postmessage
  • redirect
jsonp

原理:發起一個GET請求,回呼函數帶到請求參數中,把資料發送過去

壞處:伺服器需要支援jsoncallback參數

好處:業界比較通用的方案,包括打點等操作都可以用類似技術

瀏覽器支援:chrome/firefox/safari/opera/ie6+

client:

//jquery$(function(){    $.ajax({        url: ‘http://bbb.com:8888/crossdomain/jsonp.php‘,        dataType: ‘jsonp‘,        jsonp : ‘callback‘, //指定callback參數名        data: {name: ‘ysj‘} //資料    }).done(function(result){        alert(result) // {code:200}    })})//實際請求:http://bbb.com:8888/crossdomain/jsonp.php?callback=jQuery111108173922670539469_1410615060808&name=ysj&_=1410615060809  //native jsvar temp = document.createElement(‘script‘);temp.src = ‘http://bbb.com:8888/crossdomain/jsonp.php‘      + ‘?callback=jsonpCallback&name=ysj‘; //設定callback參數document.body.appendChild(temp)temp.parentNode.removeChild(temp);function jsonpCallback(result) {    alert(result) // {code:200}}

server:

$callback = $_GET[‘callback‘];echo $callback . "({code:200})";
hash

原理:父頁面把參數設定設定到子iframe的hash,子iframe監聽hash變化,把響應的資料設定到父頁面的hash

壞處:需伺服器對應支援,目前hash比較常用於路由,用於通訊不太合適

好處:無

瀏覽器支援:chrome/firefox/safari/opera/ie6+

代碼略

server proxy:

原理:a域請求b域,在a網域設定一個proxy伺服器指令碼頁面,接受a的參數,在通過發起一個http請求拿b域的內容,再返回給a域

壞處:在a網域服務器需要增加一個proxy頁面

好處:比較通用的方案

瀏覽器支援:chrome/firefox/safari/opera/ie6+

代碼略

window.name

原理:a域請求b域的頁面,b載入完後設定響應資料到window.name,再重新導向到a的一個頁面,此時window.name並沒有改變

壞處:b域需重新導向到a域的一個處理頁面

好處:無

瀏覽器支援:chrome/firefox/safari/opera/ie6+

代碼略

cors(跨域資源共用):

原理:伺服器設定可訪問性Access-Control-Allow-Origin: *,瀏覽器ajax取資料

壞處:需要伺服器特殊處理

好處:有比較好的未來

瀏覽器支援:chrome/firefox/safari/opera/ie10+

代碼略

postmessage:

原理:利用html5的postmessage api跨域穿資料

壞處:相容性

好處:有比較好的未來

瀏覽器支援:chrome/firefox/safari/opera/ie10+

代碼在下面跨域上傳中示範

redirect:

原理:a域iframe請求b域,把url帶上,b域把response帶上,返回到a域的handler頁面

壞處:有安全隱患

好處:簡單又瀏覽器支援良好的方案

瀏覽器支援:chrome/firefox/safari/opera/ie6+

代碼在下面跨域上傳中示範

跨域上傳
  • cors
  • redirect
  • postmessage
cors

原理:利用XMLHttpRequest2+FormData,伺服器設定Access-Control-Allow-Origin: *,跨域資源訪問這個特性,加上html5的FormData可以傳送檔案的特性。

壞處:需要伺服器設定支援跨域訪問 Access-Control-Allow-Origin: *

好處:又比較好的未來

瀏覽器支援:chrome/firefox/safari/opera/ie10+

client:

document.forms[0].onsubmit = function() {    var xhr = new XMLHttpRequest();    var data = new FormData(document.forms[0]);    xhr.open(‘POST‘ , this.action)    xhr.onload = function(){        console.log(xhr.responseText)    }    xhr.send(data)    return false}

server:

header("Access-Control-Allow-Origin: *");echo "{code:200}";
redirect

原理:a域表單提交到b域,a的表單target指向a域的一個iframe,b域重新導向到a域的結果頁面,把資料帶上。需要瀏覽器發送一個redirect參數,伺服器檢查到有這個參數,則重新導向到結果頁面,把內容帶到參數上面

壞處:伺服器和用戶端特殊參數redirect處理

好處:支援所有瀏覽器

瀏覽器支援:chrome/firefox/safari/opera/ie6+

client:

<form method="post" action="http://bbb.bbb.com:8888/crossdomain/redirect.php" target="_iframe"><input type="hidden" name="redirect" id="redirect"> <input type="file" name="Filedata"><button type="submit">submit</button></form><iframe id="_iframe" name="_iframe"></iframe>document.forms[0].onsubmit = function() {    document.getElementById(‘redirect‘).value = window.location.href.replace(/\/[^\/]*$/,‘/result.html?%s‘); //設定redirect參數值    var iframe = document.getElementById(‘_iframe‘)    iframe.onload = function(){        console.log(iframe.contentDocument             ? iframe.contentDocument.body.innerHTML             : iframe.document.body.innerHTML) // {code:200}    }}

redirect頁面

document.body.innerText=document.body.textContent=decodeURIComponent(window.location.search.slice(1)); //把參數中的資料寫入文檔

server:

$redirect = isset($_REQUEST[‘redirect‘]) ?            stripslashes($_REQUEST[‘redirect‘]) : null;$json = ‘{code:200}‘;//有redirect參數,則重新導向。需要注意的是伺服器需要設定一個白名單,符合的才給予重新導向,否則有安全問題if ($redirect) {    //頁面重新導向,把返回資料替換掉redirect url中的%s    header(‘Location: ‘.sprintf($redirect, rawurlencode($json))); }
postmessage

原理:a域準備好參數通過postmessage發送到b域的postMessageAPI頁面,這個頁面把資料用XHR+FormData的方式提交a域請求的url,postMessageAPI再把返回的資料postmesage到a域的頁面

壞處:b端伺服器需準備一個postmessageAPI頁面

好處:有比較好的未來

瀏覽器支援:chrome/firefox/safari/opera/ie10+

client:

<form method="post"><input type="file" name="Filedata" id="file"><button type="submit">submit</button></form><iframe src="http://bbb.com:8888/crossdomain/postMessage.html"></iframe>$(‘form‘).submit(function(){    var iframe = $(‘iframe‘)[0];    //向iframe的postmessate api發送訊息    iframe.contentWindow.postMessage({        url : ‘http://bbb.com:8888/crossdomain/postMessage.php‘,        dataType:‘json‘,        data : {            file : $(‘input[type=file]‘)[0].files[0] //把檔案資料傳過去        },        contentType:false,        processData:false    }, iframe.src)    return false;})//拿到postmessageAPI返回過來的訊息$(window).on(‘message‘, function(e){    var e = e.originalEvent;    alert(e.data) // {code:200}})

postmesage.html/postmessagetAPI頁面

//等待接受訊息$(window).on(‘message‘, function(e){    var e = e.originalEvent;    var options = e.data;    var truedata = options.data;    var formdata = new FormData()    for(var prop in truedata) {        formdata.append(prop,truedata[prop]);    }       options.data = formdata;    //向postmessage.php發送ajax請求,都在b域,不跨域    $.ajax(options).always(function(result){        //把響應資料再postmessage到請求的頁面        e.source.postMessage(result.responseText, e.origin)    })})

server: postMessaget.php

echo "{code:200}";
跨子域通用方案

原理:a域aaa.aaa.com,b域bbb.aaa.com。用戶端和伺服器返回都設定document.domain = ‘aaa.com‘

壞處:有安全隱患

好處:比較方便

瀏覽器支援:chrome/firefox/safari/opera/ie7+

server:

//可以設定為用戶端傳來的domain參數,但需要白名單<echo> "<script>document.domain=‘aaa.com‘</script>";<echo> "{code:200}";

此方案有個需要注意的地方:ie下面對長度小於5個字元的短網域名稱不能設定domain,例如www.uc.cn

跨域通訊/跨域上傳淺析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.