跨域

226 阅读1分钟

域名:Domain Name

同源策略:是浏览器的一个安全功能,不同源的客户脚本在没有明确授权的情况下,不能读写对方资源

只要有JS引擎的浏览器都是适用同源策略,同源策略只针对浏览器

不受同源策略限制的有:

  • 页面的超链接
  • 重定向页面
  • 表单的提交
  • 资源引入script src/link href/img src/iframe src

跨域的方式有:

1、服务器中转请求 需要后端再写api接口,调用同域名api,再利用中转服务器发送请求去请求跨域服务器中的api

2、iframe 跨域 前提是基础域名必须一致 原理:通过iframe引入一个与api同源的页面,设置共同基础域名,再调用与api同源的方法进行跨域访问api接口

3、window.name + iframe window.name 同一窗口多个页面是有共享性的,可以随意读写

原理:创建一个与源相同的html,在跨域页面中创建iframe,src=源地址页面,再通过contentWindow.location跳转到创建与源相同的html,此时将源页面中的返回数据保存在iframe.contentWindow.name中,源页面中将请求返回的数据保存在window.name中。

var flag = false;
var iframe = document.createElement('iframe');
var getDatas = function(){
  if(flag){
    var data = iframe.contentWindow.name;
    console.log(JSON.parse(data));
  }else{
    flag = true;
    setTimeout(function(){
      iframe.contentWindow.location = 'index2.html';//与源相同的html
    })
  }
}
iframe.src = 'http://test.jsplusplus.com/index.html';
if(iframe.attachEvent){
   iframe.attachEvent('onload', getDatas);
}else{
   iframe.onload = getDatas;
}
document.appendChild(iframe);

//源html:
$post("http://test.jsplusplus.com/get_course.php", {
   status: 1
}, function(data){
   window.name = JSON.stringify(data);
})

4、iframe + postmessage

5、iframe + hash

6、cors跨域

7、JSONP跨域

利用jq封装的ajax,只能用于get方式请求的数据

$.ajax({
  url: 'xxx',
  type: 'get',
  dataType: 'JSONP',
  jsonp: 'cb',//后台设置,对应的cb/callback
  success: function(data){
  	console.log(data)
  }
})

原生方式:

var oScript = document.createElement('script');
oScript.src = 'xxx?cb=test';//test自定,获取数据,然后进行保存的函数
document.body.appendChild(oScript);
document.body.removeChild(oScript);