首页 > 语言 > JavaScript > 正文

解决前端跨域问题方案汇总

2024-05-06 15:06:43
字体:
来源:转载
供稿:网友

1.同源策略如下:

URL 说明 是否允许通信
http://www.a.com/a.js
http://www.a.com/b.js
同一域名下 允许
http://www.a.com/lab/a.js
http://www.a.com/script/b.js
同一域名下不同文件夹 允许
http://www.a.com:8000/a.js
http://www.a.com/b.js
同一域名,不同端口 不允许
http://www.a.com/a.js
https://www.a.com/b.js
同一域名,不同协议 不允许
http://www.a.com/a.js
http://70.32.92.74/b.js
域名和域名对应ip 不允许
http://www.a.com/a.js
http://script.a.com/b.js
主域相同,子域不同 不允许
http://www.a.com/a.js
http://a.com/b.js
同一域名,不同二级域名(同上) 不允许(cookie这种情况下也不允许访问)
http://www.cnblogs.com/a.js
http://www.a.com/b.js
不同域名 不允许

特别注意两点:

第一,如果是协议和端口造成的跨域问题“前台”是无能为力的,
第二:在跨域问题上,域仅仅是通过“URL的首部”来识别而不会去尝试判断相同的ip地址对应着两个域或两个域是否在同一个ip上。
“URL的首部”指window.location.protocol +window.location.host,也可以理解为“Domains, protocols and ports must match”。

2. 前端解决跨域问题

1> document.domain + iframe      (只有在主域相同的时候才能使用该方法)

1) 在www.a.com/a.html中:

document.domain = 'a.com';var ifr = document.createElement('iframe');ifr.src = 'http://www.script.a.com/b.html';ifr.display = none;document.body.appendChild(ifr);ifr.onload = function(){  var doc = ifr.contentDocument || ifr.contentWindow.document;  //在这里操作doc,也就是b.html  ifr.onload = null;};

2) 在www.script.a.com/b.html中:

document.domain = 'a.com';

2> 动态创建script

这个没什么好说的,因为script标签不受同源策略的限制。

JavaScript

function loadScript(url, func) { var head = document.head || document.getElementByTagName('head')[0]; var script = document.createElement('script'); script.src = url;  script.onload = script.onreadystatechange = function(){  if(!this.readyState || this.readyState=='loaded' || this.readyState=='complete'){   func();   script.onload = script.onreadystatechange = null;  } };  head.insertBefore(script, 0);}window.baidu = { sug: function(data){  console.log(data); }}loadScript('http://suggestion.baidu.com/su?wd=w',function(){console.log('loaded')});            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选