js 跨域总结

来源:互联网 发布:淘宝网会员费 编辑:程序博客网 时间:2024/06/01 21:50

1.window.domain

强制设置相关页面 window.domain相同

a.html 

document.domain = 'a.com';

b.html

document.domain = 'a.com';


2.window.name  同一窗口,动态改变链接 window.name 是不变的,最多保留2M数据

a.html

window.name="aaaaa";

window.location.href="b.html";

b.html

alert(window.name);  //aaaaa

3.xhr

“XHR2” 全称 “XMLHttpRequest Level2” 是HTML5提供的方法,对跨域访问提供了很好的支持,并且还有一些新的功能。

* IE10以下的版本都不支持

* 只需要在服务器端头部加上下面两句代码:

header( "Access-Control-Allow-Origin:*" );

header( "Access-Control-Allow-Methods:POST,GET" );

4.jsonp

a.html

$.ajax(
    {
        type:'get',
        url : 'http://www.youxiaju.com/validate.php?loginuser=lee&loginpass=123456',
        dataType : 'jsonp',  
        jsonp:"jsoncallback", //回调方法
        success  : function(data) {
            alert("用户名:"+ data.user +" 密码:"+ data.pass);
        },
        error : function() {
            alert('fail');
        }
    }
);

function jsoncallback(data){

//dosomesing

}


5 postMessage

a.html

window.onload = function() {    var ifr = document.getElementById('ifr');    var targetOrigin = 'http://b.com';  // 若写成'http://b.com/c/proxy.html'效果一样                                        // 若写成'http://c.com'就不会执行postMessage了    ifr.contentWindow.postMessage('I was there!', targetOrigin);};

b.html

window.addEventListener('message', function(event){        // 通过origin属性判断消息来源地址        if (event.origin == 'http://a.com') {            alert(event.data);    // 弹出"I was there!"            alert(event.source);  // 对a.com、index.html中window对象的引用                                  // 但由于同源策略,这里event.source不可以访问window对象        }    }, false);

6.web sockets


原创粉丝点击