HTML5:使用postMessage實現Ajax跨域請求

來源:互聯網
上載者:User

標籤:blog   http   io   ar   os   使用   java   sp   for   

HTML5:使用postMessage實現Ajax跨域請求

由於同源策略的限制,Javascript存在跨域通訊的問題,典型的跨域問題有iframe與父級的通訊等。

常規的幾種解決方案:
(1) document.domain+iframe; (2) 動態建立script; (3) iframe+location.hash; (4) flash。

這裡不細說這幾種方法,記錄的是HTML5的window.postMessage。postMessage相容IE8+、Firefox、Opera、Safari、Chrome。

需要兩個異域的伺服器來做測試,當然也可以用本地和線上伺服器作為兩個異域的伺服器。假如使用phonegap開發,就可以將請求檔案安裝在用戶端,然後動態請求伺服器的資料處理,獲得並顯示資料。這樣就可以用任意Web開發語言及方法來開發phonegap App所需的後台。
1.  postMessage的用法

postMessage是HTML5為解決js跨域問題而引入的新的API,允許多個iframe/window跨域通訊。

假設有結構如下:

test.html

Js代碼  
  1. <section id="wrapper">  
  2.   <header>  
  3.     <h1>postMessage (跨域)</h1>  
  4.   </header>  
  5.   <article>  
  6.     <form>  
  7.       <p>  
  8.         <label for="message">給iframe發一個資訊:</label>  
  9.         <input type="text" name="message" value="son" id="message" />  
  10.         <input type="submit" />  
  11.       </p>  
  12.     </form>  
  13.     <h4>目標iframe傳來的資訊:</h4>  
  14.     <p id="test">暫無資訊</p>  
  15.     <iframe id="iframe"  
  16.     src="http://xiebiji.com/works/postmessage/iframe.html"></iframe>  
  17.   </article>  
  18. </section>  



  

iframe.html

Js代碼  
  1. <strong>iframe指向xiebiji.com</strong>  
  2. <form>  
  3.   <p>  
  4.     <label for="message">給父視窗發個資訊:</label>  
  5.     <input type="text" name="message" value="dad" id="message" />  
  6.     <input type="submit" />  
  7.   </p>  
  8. </form>  
  9. <p id="test">暫無資訊。</p>  


下面是test.html裡的Javascript代碼(發送資料):

Js代碼  
  1. var win = document.getElementById("iframe").contentWindow;  
  2. document.querySelector(‘form‘).onsubmit=function(e){  
  3.   win.postMessage(document.getElementById("message").value,"*");  
  4.   if (e.preventDefault)  
  5.     e.preventDefault();  
  6.   e.returnValue = false;  
  7. }  




  關鍵代碼就一句:

win.postMessage(document.getElementById("message").value,"*");

  postMessage是通訊對象的一個方法,所以向iframe通訊,就是iframe對象調用postMessage方法。postMessage有兩個參數,缺一不可。第一個參數是要傳遞的資料,第二個參數是允許通訊的域,“*”代表不對訪問的域進行判斷,可理解為允許所有域的通訊。

  然後是iframe.html裡偵聽接收資料的代碼:

Js代碼  
  1. var parentwin = window.parent;  
  2. window.onmessage=function(e){  
  3.   document.getElementById("test").innerHTML = e.origin + "say:" + e.data;  
  4.   parentwin.postMessage(‘HI!你給我發了"<span>‘+e.data+‘"</span>。‘,"*");  
  5. };  



  很簡單,相信一看就懂了。e.data包含傳送過來的資料,e.origin指代源域。

然後iframe.html也給test.html發送回應的資料,test.html接收資料。代碼雷同,就不貼代碼了。
 
2. Ajax跨域請求

基於以上的跨域通訊,只要將Ajax代碼放在iframe.html裡的onmessage處理函數裡頭,將test.html用postMessage傳過來的資料作為參數發送請求,再將返回的資料用postMessage傳給test.html。這樣就實現了跨域的Ajax請求。其實是很簡單的東西。

貼個範例程式碼吧,但跟以上的代碼無關。

Js代碼  
    1. (function(){  
    2.   //擷取跨域資料  
    3.   window.onmessage = function(e){  
    4.     var url = "http://yangzebo.com/demo/noforget/test.php?msg=" + e.data;  
    5.     //Ajax  
    6.     var xhr = getXHR();  
    7.     if(xhr){  
    8.       xhr.open("GET",url,true);  
    9.       xhr.onreadystatechange = changeHandle;  
    10.       xhr.send(null);  
    11.     }else{  
    12.      alert("不支援Ajax");  
    13.     }  
    14.     function changeHandle(){//返回處理  
    15.       if(xhr.readyState == 4){  
    16.         var parentwin = window.parent;  
    17.         parentwin.postMessage(xhr.responseText,"*");//跨域發送資料  
    18.       }  
    19.     }  
    20.     function getXHR(){//擷取XMLHttpRequest  
    21.       var xhr_temp;  
    22.       if(window.XMLHttpRequest){  
    23.         xhr_temp = new XMLHttpRequest();  
    24.       }else if(window.ActiveXObject){  
    25.         xhr_temp = new ActiveXObject("Microsoft.XMLHTTP");  
    26.       }else{  
    27.         xhr_temp = null;  
    28.       }  
    29.       return xhr_temp;  
    30.     }  
    31.   };  
    32. })(); 
    33. 一看就懂,就特記錄下來以供學習
    34. 原文見:http://wangdf-jee.iteye.com/blog/1404272

HTML5:使用postMessage實現Ajax跨域請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.