转自:http://www.cnblogs.com/JChen666/p/3399951.html
1.同源策略如下:
@H_502_102@ @H_502_102@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引入的内容