前端解决跨域问题的8种方案(最新最全)
发布时间:2020-12-17 09:36:26 所属栏目:安全 来源:网络整理
导读:转自:http://www.cnblogs.com/JChen666/p/3399951.html 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 同一域名下不同文件夹 允许 ht
转自:http://www.cnblogs.com/JChen666/p/3399951.html 1.同源策略如下:
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标签不受同源策略的限制。 function loadScript(url,func) { var head = document.head || document.getElementByTagName('head')[0]; var script = document.createElement('script'); script.src = url; script.onload = script.onreadystatechange = 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')}); 我们请求的内容在哪里? //我们可以在chorme调试面板的source中看到script引入的内容
3> location.hash + iframe原理是利用location.hash来进行传值。 假设域名a.com下的文件cs1.html要和cnblogs.com域名下的cs2.html传递信息。 function startRequest(){
var ifr = document.createElement('iframe');
ifr.style.display = 'none';
ifr.src = 'http://www.cnblogs.com/lab/cscript/cs2.html#paramdo';
document.body.appendChild(ifr);
}
function checkHash() {
try {
var data = location.hash ? location.hash.substring(1) : '';
if (console.log) {
console.log('Now the data is '+data);
}
} catch(e) {};
}
setInterval(checkHash,2000);
|