高分悬赏-js获取跨域iframe中返回值(xml)并处理解决方案.doc
文本预览下载声明
高分悬赏:js获取跨域iframe中返回值(xml)并处理解决方案
篇一:前端解决跨域问题的8种方案(最新最全)
1) 在/a.html中:
document.domain = #39;#39;;
varifr = document.createElement(#39;iframe#39;);
ifr.src= #39;/b.html#39;;
ifr.display= none;
document.body.appendChild(ifr);
ifr.onload= function(){
var doc = ifr.contentDocument ||ifr.contentWindow.document; //在这里操作doc,也就是b.html
ifr.onload = null; };
2) 在/b.html中:
document.domain = #39;#39;;
这个没什么好说的,因为script标签不受同源策略的限制。
functionloadScript(url, func) {
var head = document.head || document.getElementByTagName(#39;head#39;)[0]; var script = document.createElement(#39;script#39;);
script.src=url;
script.onload= script.oeadystatechange = function(){
if(!this.readyState || this.readyState==#39;loaded#39; ||
this.readyState==#39;complete#39;){
func();
script.onload= script.oeadystatechange = null;
}
};
head.insertBefore(script, 0);
}
window.baidu= {
sug: function(data){
console.log(data);
}
}
loadScript(#39;/su?wd=w#39;,function(){console.log(#39;loaded#39;)});
//我们请求的内容在哪里?
//我们可以在chorme调试面板的source中看到script引入的内容
原理是利用
location.hash来进行传值。
假设域名下的文件cs1.html要和域名下的cs2.html传递信息。
1) cs1.html首先创建自动创建一个隐藏的iframe,iframe的src指向域名下的cs2.html页面
2) cs2.html响应请求后再将通过修改cs1.html的hash值来传递数据
3) 同时在cs1.html上加一个定时器,隔一段时间来判断location.hash的值有没有变化,一旦有变化则获取获取hash值
注:由于两个页面不在同一个域下IE、Chrome不允许修改parent.location.hash的值,所以要借助于域名下的一个代理iframe
代码如下:
先是下的文件cs1.html文件:
functionstartRequest(){
varifr = document.createElement(#39;iframe#39;);
ifr.style.display= #39;none#39;;
ifr.src= #39;/lab/cscript/cs2.html#paramdo#39;; document.body.appendChild(ifr);
}
functioncheckHash() {
try {
var data = location.hash ? location.hash.substring(1) : #39;#39;;
if (console.log) {
console.log(#39;Now the data is #39;+data);
}
} catch(e) {};
}
setInterval(checkHash, 2000);
域名下的cs2.html:
//模拟一个简单的参数处理操作
switch(location.hash
){
case #39;#paramdo#39;:
callBack();
break;
case #39;#paramset#39;:
//do something……
break;
}
functioncallBack(){
try {
parent.locatio
显示全部