js实现跨域(jsonp, iframe+window.name, iframe+window.domain, iframe+window.postMessage)

1、浏览器同源策略javascript

首先咱们须要了解一下浏览器的同源策略,关于同源策略能够仔细看看知乎上的一个解释。传送门
php

总之:同协议,domain(或ip),同端口视为同一个域,一个域内的脚本仅仅具备本域内的权限,能够理解为本域脚本只能读写本域内的资源,而没法访问其它域的资源。这种安全限制称为同源策略。html

( 现代浏览器在安全性和可用性之间选择了一个平衡点。在遵循同源策略的基础上,选择性地为同源策略"开放了后门"。 例如img script style等标签,都容许垮域引用资源。)html5

下表给出了相对 http://store.company.com/dir/page.html 同源检测的示例:java

URL 结果 缘由
http://store.company.com/dir2/other.html 成功  
http://store.company.com/dir/inner/another.html 成功  
https://store.company.com/secure.html 失败 协议不一样
http://store.company.com:81/dir/etc.html 失败 端口不一样(默认80)
http://news.company.com/dir/other.html 失败 主机名不一样

 

 

 

 

 

 

 

 

 

 

因为浏览器同源策略的限制,让咱们没法经过js直接在不一样的域之间进行数据传输或通讯,好比用ajax向一个不一样的域请求数据,或者经过js获取页面中不一样域的框架(iframe)中的数据。git

2、jsonp实现跨域请求数据github

在javascript中,咱们不能直接用ajax请求不一样域上的数据。可是,在页面上引入不一样域上的js脚本文件倒是能够的,jsonp正是利用这个特性来实现的。web

本地测试利用PHP内置了的Web 服务器来模拟两个端口不一样的两个域,如今在web_test目录下有9000和9001两个目录,分别进入两个目录执行ajax

web_test/9000: php -S 127.0.0.1:9000
web_test/9001: php -S 127.0.0.1:9001

执行后:chrome

 

这时候开启了两个本地不一样端口的服务器,如今在两个目录下的文件就是在两个不一样域。

 在9001目录下jsonp_test.html中

<!DOCTYPE html>
<html>
<head>
    <title>jsonp-test</title>
</head>
<body>
    <script type="text/javascript">
        function callback_data (data) {
            console.log(data);
        }
    </script>
    <script type="text/javascript" src="http://127.0.0.1:9000/jsonp.php?callback=callback_data"></script>
</body>
</html>

能够看到咱们在向9000目录下的jsonp.php文件获取数据时,地址后面跟了一个callback参数(通常的就是用callback这个参数名,你也能够用其余的参数名代替)。

若是你要获取数据的页面是你不能控制的,那你只能根据它所提供的接口格式进行获取。

由于咱们的type规定是当成是一个javascript文件来引入的,因此php文件返回的应该是一个可执行的js文件。

 在9000目录下jsonp.php中

<?php
    $callback = $_GET['callback'];  // 获取回调函数名
    $arr = array("name" => "alsy", "age" => "20"); // 要请求的数据
    echo $callback."(". json_encode($arr) .");"; // 输出
?>

页面输出就是这样的:

callback_data({"name":"alsy","age":"20"}); //执行url参数中指定的函数,同时把咱们须要的json数据做为参数传入

 这样咱们浏览器中输入http://127.0.0.1:9001/jsonp_test.html,控制台打印出:

这样咱们就获取到不一样域中返回的数据了,同时jsonp的原理也就清楚了:

经过script标签引入一个js文件,这个js文件载入成功后会执行咱们在url参数中指定的函数,同时把咱们须要的json数据做为参数传入。因此jsonp是须要服务器端和客户端相互配合的。

知道jsonp跨域的原理后咱们就能够用js动态生成script标签来进行跨域操做了,而不用特地的手动的书写那些script标签。好比jQuery封装的方法就能很方便的来进行jsonp操做了。

9001目录下的html中:

//$.getJSON()方法跨域请求
$.getJSON("http://127.0.0.1:9000/jsonp.php?callback=?", function(data){
    console.log(data);
});

原理是同样的,只不过咱们不须要手动的插入script标签以及定义回掉函数。jQuery会自动生成一个全局函数来替换callback=?中的问号,以后获取到数据后又会自动销毁,实际上就是起一个临时代理函数的做用。

从请求的url和响应的数据就能够很明显的看出来了:

这里的 jQuery214036133305518887937_1462698255551 就是一个临时代理函数。

$.getJSON方法会自动判断是否跨域,不跨域的话,就调用普通的ajax方法;跨域的话,则会以异步加载js文件的形式来调用jsonp的回调函数。

另外jsonp是没法post数据的,尽管jQuery.getJSON(url, [data], [callback]); 提供data参数让你能够携带数据发起请求,但这样是以get方式传递的。好比:

9001目录下的html中:

//$.getJSON()方法
$.getJSON("http://127.0.0.1:9000/jsonp.php?callback=?", {u:'abc', p: '123'}, function(jsonData){
    console.log(jsonData);
});

或者是调用$.ajax()方法指定type为post,它仍是会转成get方式请求。

9001目录下的html中:

$.ajax({
type: 'post',
url: "http://127.0.0.1:9000/jsonp_post.php",
crossDomain: true,
data: {u: 'alsy', age: 20},
dataType: "jsonp",
success: function(r){
console.log(r);
}
});

以get形式的话是能够携带少许数据,可是数据量一大就不行了。

若是想post大量数据,就能够尝试用CORS(跨域资源共享,Cross-Origin Resource Sharing)。传送门

CORS定义一种跨域访问的机制,可让AJAX实现跨域访问。CORS 容许一个域上的网络应用向另外一个域提交跨域 AJAX 请求。实现此功能很是简单,只需由服务器发送一个响应标头便可。

即服务器响应头设置

    header('Access-Control-Allow-Origin: *'); // "*"号表示容许任何域向服务器端提交请求;也能够设置指定的域名,那么就容许来自这个域的请求:
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Max-Age: 1000');

好比:

9001目录下的一个html文件:

$.ajax({
    type: 'post',
    url: "http://127.0.0.1:9000/jsonp_post.php",
    crossDomain: true,
    data: {u: 'alsy', age: 20},
    dataType: "json",
    success: function(r){
        console.log(r);
    }
});

9000目录下的php文件:

<?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST');
    header('Access-Control-Max-Age: 1000');
    if($_POST){
        $arr = array('name' => $_POST['u'], 'age' => $_POST['age']);
        echo json_encode($arr);
    } else {
        echo json_encode([]);
    }
?>

浏览器显示:

这样也是能够实现跨域post数据的。

  1. 兼容性。CORS是W3C中一项较新的方案,因此部分浏览器尚未对其进行支持或者完美支持,详情可移至 http://www.w3.org/TR/cors/
  2. 安全问题。CORS提供了一种跨域请求方案,但没有为安全访问提供足够的保障机制,若是你须要信息的绝对安全,不要依赖CORS当中的权限制度,应当使用更多其它的措施来保障。

3、iframe+window.domain 实现跨子域

 如今9001目录下有一个iframe-domain.html文件:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>127.0.0.1:9001 -- iframe-domain</title>
</head>
<body>
<h1>127.0.0.1:9001/iframe-domain.html</h1>
<script>  
function test(){ var obj = document.getElementById("iframe").contentWindow; //获取window对象 console.log(obj); } </script> <iframe id="iframe" src="http://127.0.0.1:9000/domain.html" onload="test()"></iframe> </body> </html>

在这个页面中存在一个不一样域的框架(iframe),而iframe载入的页面是和目标域在同一个域的,是可以向目标域发起ajax请求获取数据的。

那么就想能不能控制这个iframe让它去发起ajax请求,但在同源策略下,不一样域的框架之间也是不可以进行js的交互。

虽然不一样的框架之间(父子或同辈),是可以获取到彼此的window对象的,可是却不能获取到的window对象的属性和方法(html5中的postMessage方法是一个例外,还有些浏览器好比ie6也可使用top、parent等少数几个属性),总之就是获取到了一个无用的window对象。

在这个时候,document.domain就派上用场了,咱们只要两个域的页面的document.domain设置成同样了,这个例子中因为端口不一样,两边的document.domain也要从新设置成"127.0.0.1",才能正常通讯。

要注意的是,document.domain的设置是有限制的,咱们只能把document.domain设置成自身更高一级的父域主域必须相同。

另举例:a.b.example.com 中某个文档的document.domain 能够设成a.b.example.com、b.example.com 、example.com中的任意一个;

可是不能够设成c.a.b.example.com,由于这是当前域的子域,也不能够设成baidu.com,由于主域已经不相同了。

经过设置document.domain为相同,如今已经可以控制iframe载入的页面进行ajax操做了。

9001目录下的iframe-domain.html文件改成:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>127.0.0.1:9001 -- iframe-domain</title>
</head>
<body>
<h1>127.0.0.1:9001/iframe-domain.html</h1>
<script> document.domain = '127.0.0.1'; //设置domain function test(){
        var obj = document.getElementById("iframe").contentWindow;
        console.log(obj);
        obj.getData('http://127.0.0.1:9000/json_domain.php', '{u: "alsy-domain", age: "20"}', function(r){
            console.log(  eval("("+ r +")") );
        });
    }
</script>
<iframe id="iframe" src="http://127.0.0.1:9000/domain.html" onload="test()"></iframe>
</body>
</html>

 

9000目录下有一个domain.html,和一个json_domain.php文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>domain</title>
</head>
<body>
<h1>127.0.0.1/9000/domain.html</h1>
<script>
    window.onload = function(){
        document.domain = '127.0.0.1'; //设置domain
        window.getData =  function(url, data, cb) {
            var xhr = null;
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xhr.open('POST', url, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    cb(xhr.responseText);
                }
            }
            xhr.send(data);
        }
    }
</script>
</body>
</html>
<?php
    $str = file_get_contents('php://input');
    echo json_encode($str);
?>

浏览器打印:

这样就能够实现跨域,固然你也能够动态建立这么一个iframe,获取完数据后再销毁。

4、iframe+window.name 实现跨域

window对象有个name属性,该属性有个特征:即在一个窗口(window)的生命周期内,窗口载入的全部的页面都是共享一个window.name的,每一个页面对window.name都有读写的权限。(window.name的值只能是字符串的形式,这个字符串的大小最大能容许2M左右甚至更大的一个容量,具体取决于不一样的浏览器,通常够用了。)

9001目录下的iframe-window.name.html:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>127.0.0.1:9001 -- iframe-window.name</title>
</head>
<body>
<h1>127.0.0.1:9001/iframe-window.name.html</h1>
<script>
    function test(){
        var obj = document.getElementById("iframe");
        obj.onload = function(){
            var message = obj.contentWindow.name;
            console.log(message);
        }
        obj.src = "http://127.0.0.1:9001/a.html";
    }
</script>
<iframe id="iframe" src="http://127.0.0.1:9000/window.name.html" onload="test()"></iframe>
</body>
</html>

9000目录下的window.name.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>window.name</title>
</head>
<body>
<h1>127.0.0.1/9000/window.name.html</h1>
<script>
    //todo
    window.name = "This is message!";
</script>
</body>
</html>

浏览器输出:

整个跨域的流程就是:如今9000/window.name.html中经过一些操做将数据存入window.name中了,而9001/iframe-window.name.html想要获取到window.name的值就须要依靠iframe做为中间代理,首先把iframe的src设置成http://127.0.0.1:9000/window.name.html,这样就至关于要获取iframe的window.name,而要想获取到iframe中的window.name,就须要把iframe的src设置成当前域的一个页面地址"http://127.0.0.1:9001/a.html",否则根据前面讲的同源策略,window.name.html是不能访问到iframe里的window.name属性的。

5、iframe+window.postMessage 实现跨域

html5炫酷的API之一:跨文档消息传输。高级浏览器Internet Explorer 8+, chrome,Firefox , Opera  和 Safari 都将支持这个功能。这个功能实现也很是简单主要包括接受信息的"message"事件和发送消息的"postMessage"方法。

发送消息的"postMessage"方法:

向外界窗口发送消息:

otherWindow.postMessage(message, targetOrigin);

otherWindow:  指目标窗口,也就是给哪一个window发消息。

message: 要发送的消息,类型为 String、Object (IE八、9 不支持)

targetOrigin: 是限定消息接收范围,不限制请使用 '*'

接受信息的"message"事件

var onmessage = function (event) {
    var data = event.data;
    var origin = event.origin;
    //do someing
};
if (typeof window.addEventListener != 'undefined') {
    window.addEventListener('message', onmessage, false);
} else if (typeof window.attachEvent != 'undefined') {
    //for ie
    window.attachEvent('onmessage', onmessage);
}

回调函数第一个参数接收 event 对象,有三个经常使用属性:

  • data:  消息
  • origin:  消息来源地址
  • source:  源 DOMWindow 对象

 9000目录下的 postmessage.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>postmessage</title>
</head>
<body>
<h1>127.0.0.1/9000/postmessage.html</h1>
<script>
    window.onload = function () {
        if (typeof window.postMessage === undefined) {
            alert("浏览器不支持postMessage!");
        } else {
            window.top.postMessage({u: "alsy"}, "http://127.0.0.1:9001");
        }
    }
</script>
</body>
</html>

 9001目录下的 iframe-postmessage.html:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>127.0.0.1:9001 -- iframe-postmessage</title>
</head>
<body>
<h1>127.0.0.1:9001/iframe-postmessage.html</h1>
<script>
    function test(){
        if (typeof window.postMessage === undefined) {
            alert("浏览器不支持postMessage!");
        } else {
            window.addEventListener("message", function(e){
                if (e.origin == "http://127.0.0.1:9000") { //只接收指定的源发来的消息
                    console.log(e.data);
                };
            }, false);
        }
    }
</script>
<iframe id="iframe" src="http://127.0.0.1:9000/postmessage.html" onload="test()"></iframe>
</body>
</html>

浏览器打印:

 6、说明

参考自 http://www.cnblogs.com/2050/p/3191744.html

若有错误或不一样观点请指出,共同交流。

完整代码:传送门

相关文章
相关标签/搜索