码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript跨域

时间:2017-03-12 17:48:36      阅读:130      评论:0      收藏:0      [点我收藏+]

标签: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跨域

标签:images   class   属性   str   logs   ons   window   回调函数   stat   

原文地址:http://www.cnblogs.com/shen076/p/6538473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!