xwcueh 发表于 2013-1-29 08:57:12

iframe跨域取数据

大家好:
    这是我的第一篇博客文章,围观有奖,围观有奖!
    好了,废话少说,进入主题,前段时间遇到了一个问题:
    我在页面里嵌套了一个iframe,iframe连接的是一个异域的地址,花了不少的时间没有发现是什么原因,原以为是js获取iframe页面的dom元素出的问题,居然忽略了是跨域的问题。

    有关iframe获取元素也是很容易出问题,我就借此机会将所有有关父页面获取iframe元素,以及iframe获取父页面的方法详细罗列一下,并介绍一个比较不错的跨域取元素的方法:

1.从父页面取iframe窗口:(存在跨域访问限制)
    11.window.frames;
    22.document.getElementById('ifr').contentWindow;
    以上两种方法对所有的浏览器有效。

2.获取iframe的document:(存在跨域访问限制)
    21.document.getElementById('ifr').contentDocument;
    22.document.getElementById('ifr').contentWindow.document;
    33.window.frames.document;
    网上有些资料写的是contentWindow只对ie有效,contentDocument只对非ie浏览器有效,但是经过我的测试,这两种方法是对当前主流浏览器有效的(ie,firefox,chrome,safari,opera)

3.iframe获取父窗口:(存在跨域访问限制)
    31.window.parent;(获取一级父窗口)
    32.window.top;(获取顶级窗口)

下面我讲两种跨域访问的例子:


js跨域访问:

    js跨域访问dom元素是被禁止的,比如:a.com访问b.com以及a.com访问b.a.com的dom元素都是访问不到的,但是js文件是允许访问的,利用这个特点实现跨域。
    下面贴上代码:

a.com域的test.html代码:
<input type="button" value="跨域测试" /><input type="button" value="test2" /><div id="ttt">cosplay</div>

   function loadScript(url){var lastScript;var script = document.createElement("script");var id = new Date().getTime();script.src = url;script.type = "text/javascript";script.id = id;if(!script && g(lastScript))g(lastScript).parentNode.removeChild(g(lastScript));lastScript = id;document.head.appendChild(script);   }   function g(x){return document.getElementById(x);   }
b.com的test2.js代码:
function test2(){var tt = document.getElementById("ttt").innerHTML;alert(tt);}
    通过127.0.0.1访问a.com的test.html就与b.com(localhost)不在一个域中了,点击跨域测试获取js代码,点击test2可访问从b.com获取的js,正常情况下应该输出cosplay,这种方法跨域比较简单,在js里准备好数据传递给异域的页面,比较起jsonP和代理跨域更简单



sonP跨域访问数据:

域一:使用127.0.0.1访问test.html的代码:
   $.ajax({url:"http://localhost:8080/*****/MH.action",type:"post",dataType:"jsonp",jsonp:"callback",cache:"false",async:"false",data:{自己传递数据},success:function(data){alert(data.name);}   })
上面的$.ajax访问的url是localhost与127.0.0.1是不同的域
其中MH.action的代码:
public String execute() {JSONObject res = new JSONObject();res.put("name", "郭德纲");PrintWriter pw;try {pw = Struts2Utils.getResponse().getWriter();String callback = Struts2Utils.getRequest().getParameter("callback");Struts2Utils.getResponse().setContentType("text/html");Struts2Utils.getResponse().setCharacterEncoding("utf-8");pw.print(callback + "("+res.toString()+")");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}
Struts2Utils是自己的类,request,response自己获取即可
运行test.html会输出“郭德纲”。异域获取数据成功!
页: [1]
查看完整版本: iframe跨域取数据