js跨域问题

来源:互联网 发布:淘宝新店没流量 编辑:程序博客网 时间:2024/05/02 01:33

什么是跨域?

概念:只要协议、域名、端口有任何一个不同,都被当作是不同的域。

简单明了,不明白的话可以百度百科,额。。。。。。

1.document.domain(跨子域)

这个是范围最小的一个。

比如a.example.com 中写了一个iframe,其中src="example.com",但是因为是不同域的就无法写js获取iframe中的document等。

这时设置document.domain=“example.com”就可以了。

但document.domain的设置是有限制的,必须是本身或者比是本身的父域。

2.window.name

例如在a.com/yyy.html页面要获取b.com/xxx.html中的数据

function domainData(url, fn)    {        var isFirst = true;        var iframe = document.createElement('iframe');        iframe.style.display = 'none';        var loadfn = function(){            if(isFirst){                iframe.contentWindow.location = 'http://a.com/null.html';//其中这个是个空文件                isFirst = false;            } else {                fn(iframe.contentWindow.name);                iframe.contentWindow.document.write('');                iframe.contentWindow.close();                document.body.removeChild(iframe);                iframe.src = '';                iframe = null;            }        };        iframe.src = url;        if(iframe.attachEvent){            iframe.attachEvent('onload', loadfn);        } else {            iframe.onload = loadfn;        }        document.body.appendChild(iframe);    }    domainData('http://example.com/', function(data){        alert(data);    });

b.com/xxx.html中:

window.name = "要传输的数据"(可以是JSON,最大2M)

3.H5的window.postMessage(message,targetOrigin)

4.jsonp

举一个jquery、node的例子

$.ajax({            url: "http://192.168.1.100:10011?callback=?",            dataType: 'jsonp',            type: 'get',            success: function(res){                $('#result').val('My name is: ' + res);                console.log(res);            },            error: function(){            }        });
node部分:

var http = require('http');var urllib = require('url');var port = 10011;var data = {    'name': 'hqq',    'age': 22};http.createServer(function(req, res){    var params = urllib.parse(req.url, true);    console.log(params);    if (params.query && params.query.callback) {        var str =  params.query.callback + '(' + JSON.stringify(data) + ')';//jsonp        res.end(str);    } else {        res.end(JSON.stringify(data));//普通的json        console.log(JSON.stringify(data));    }}).listen(port, function(){    console.log('server is listening on port ' + port);});

设个断点发现jsonp的原理是动态插入script标签,添加属性src="跨域地址"。然后在url后边加入一个JSONPcallback=functionName,这样后端就能识别出是jsonp请求,返回一个函数名为functionName的函数,其中JSON以入参的形式放入函数中,只支持get请求

(其实JSONP的原理就是动态插入标签而已,没有使用XMLHttpRequest)

5.CORS

使用XMLHttpRequest,get/post请求都支持。

原理是在服务器端设置头部如下:

http.createServer(function(req, res){    res.writeHead(200,{"Access-Control-Allow-Origin": "*"});}
或者

res.writeHead(200,{"Access-Control-Allow-Origin": "http://localhost:63342"});

浏览器检测到这个头部,就比较一下自己的域名和头部给的允许域名是否一样,一样就允许访问。

OK!!!


0 0
原创粉丝点击