以下的例子包含的文件均为为 、 与 ,要做的都是从a.html获取b.html里的数据
1.JSONP
jsonp是利用script标签没有跨域限制的特性,通过在src的url的参数上附加回调函数名字,然后服务器接收回调函数名字并返回一个包含数据的回调函数
// 2.服务器根据 callback 这个参数生成一个包含数据的函数 doSomething({"a","1"})
// 3.页面事先已声明doSomething函数,此时执行 doSomething(data) 这个函数,获得数据
2.HTML5的postMessage
a.html
window.frames[0].postMessage("b data","http://www.b.com/b.html");
}
b.html
这样打开a页面就先弹出 a data,再弹出 b data
3.window.name + iframe
window.name的原理是利用同一个窗口在不同的页面共用一个window.name,这个需要在a.com下建立一个代理文件c.html,使同源后a.html能获取c.html的window.name
a.html
var flag = true;
iframe.onload = function() {
if (flag) {
iframe.src = "c.html";
// 判断是第一次载入的话,设置代理c.html使和a.html在同目录同源,这样才能在下面的else取到data
flag = false;
} else { // 第二次载入由于a和c同源,a可以直接获取c的window.name
alert(iframe.contentwindow.name);
iframe.conten<a href="https://www.jb51.cc/tag/twind/" target="_blank" class="keywords">twind</a>ow.close();
document.body.removeChild(iframe);
iframe.src = '';
iframe = null;
}
}
b.html
4.window.location.hash + iframe
b.html将数据以hash值的方式附加到c.html的url上,在c.html页面通过location.hash获取数据后传到a.html(这个例子是传到a.html的hash上,当然也可以传到其他地方)
a.html
b.html
c.html
5.CORS
CORS是XMLHttpRequest Level 2 里规定的一种跨域方式。在支持这个方式的浏览器里,javascript的写法和不跨域的ajax写法一模一样,只要服务器需要设置Access-Control-Allow-Origin: *
6.document.domain
这种方式适用于主域相同,子域不同,比如和 假如这两个域名下各有a.html 和b.html,
a.html
b.html
注意:document.domain需要设置成自身或更高一级的父域,且主域必须相同。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。