ajax主域和子域之間的跨域問題

來源:互聯網
上載者:User

標籤:屬性   frame   java   htm   ajax   splay   bar   function   方式   

在某些應用情境下,需要在主域中,調用子域中的某個介面,如果直接在主域中向子域發ajax請求,會報跨域錯誤,可以用iframe來解決這種跨域問題。
假如主域為www.baidu.com,子域為baike.baidu.com。主域中的A頁面需要通過ajax請求調用子域中的某項服務。首先需要在子域中準備一個B頁面,B頁面就是一個簡單的空頁面,最好把jquery引到B頁面中,這樣可以直接用jquery發ajax請求;在主域的A頁面中要用iframe把B頁面url地址引過來。

B頁面格式

 1 //B.html 2 <html> 3 <head> 4     <title>B頁面</title> 5     <script type="text/javascript" src="jquery.js"></script> 6 </head> 7 <body> 8     <div>B頁面</div> 9     <script>        10         $(function(){11             try{12             document.domain = "www.baidu.com";13             }catch(e){}14         });15     </script>16 </body>17 </html>

A頁面格式

 1 //A.html 2 <html> 3 <head> 4     <title>A頁面</title> 5     <script type="text/javascript" src="jquery.js"></script> 6 </head> 7 <body> 8     <div>A頁面</div> 9     <iframe id="iframe" src="http://baike.baidu.com/B.html" style="display:none;"></iframe>10     <script>11         $(function(){12             try{13                 document.domain = "www.baidu.com";14             }catch(e){}15             $("#iframe").load(function(){16                 var iframe = $("#iframe").contentDocument.$;17                 ifram.get("http://baike.baidu.com/介面",function(data){});18             });19         });20     </script>21 <body>22 </html>

有一點需要注意,就是在A頁面中,要等iframe標籤完成載入B頁面之後,再取iframe對象的contentDocument,否則如果B頁面沒有被iframe完全載入,在A頁面中通過contentDocument屬性就取不到B頁面中的jQuery對象。一旦取到B頁面中的jQuery對象,就可以直接發ajax請求了,這種類似“代理”方式可以解決主子域的跨域問題。

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.