JavaScript跨域

來源:互聯網
上載者:User

標籤:images   class   屬性   str   logs   ons   window   回呼函數   stat   

只要協議、網域名稱、連接埠有任何一個不同,都被當作是不同的域。

也就是“http://www.baidu.com”這個URL首部,必須完全一樣才能互相通訊。

一、通過jsonp跨域

原理:不同的域可以傳輸JS檔案

伺服器的data.php:

<?php$callback=$_GET[‘callback‘];//得到的回呼函數名$data=array(‘a‘,‘b‘,‘c‘);//需要返回的資料echo $callback.‘(‘.json_encode($data).‘)‘;//輸出?>

HTML:

<!DOCTYPE html><html><head>    <meta charset="utf-8">    <title>跨域</title> </head><body><script>    function dosomething(jsondata){        console.log(jsondata)    }</script><script src=‘http://oa.daoyoudashi.com/shen/data.php?callback=dosomething‘></script></body></html>

或者用jquery:

<!DOCTYPE html><html><head>    <meta charset="utf-8">    <title>跨域</title>    <script src="http://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js"></script>  </head><body><script>$.getJSON("http://oa.daoyoudashi.com/shen/data.php?callback=?", function(jsondata) {    console.log(jsondata);});</script></body></html>

結果:

["a","b","c"]

 

2、通過修改document.domain來跨子域

伺服器中的a.html

<!DOCTYPE html><html><head>    <meta charset="utf-8">    <title>a跨域</title></head><body><script>function onLoad(){    var iframe=document.getElementById(‘iframe‘);    console.log(iframe);    var win=iframe.contentWindow;    console.log(win);    var doc=win.document;    console.log(doc);    var name=win.name;     console.log(name); //無法擷取window對象的name屬性}</script><iframe id="iframe" src="http://oa.daoyoudashi.com/shen/b.html" onload="onLoad()"></iframe></body></html>

伺服器中的b.html

<!DOCTYPE html><html><head>    <meta charset="utf-8">    <title>b跨域</title>  </head><body><div>內容</div></body></html>

結果:

 

JavaScript跨域

聯繫我們

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