【问题标题】:Calling parent window method from Iframe从 iframe 调用父窗口方法
【发布时间】:2013-02-28 05:49:39
【问题描述】:

我知道这是跨浏览器通信或同源策略的问题,浏览器不允许此类通信。

我需要解决这个用例。我在 HTTP 中有一个父页面,从那里我将表单提交到 HTTPS,我的要求是不要离开页面并且表单在覆盖中打开.

这是我当前的 JSP 设置

<form:form action="https://localhost:9002/myApp/springSecurity/login" class="login-form error-info"  id="loginForm"  method="post" commandName="loginForm" target="guestFrame">

 <iframe width="0" frameborder="0" scrolling="no" name="guestFrame" >

我在服务器上发送 java 脚本以附加到 iframe 上,这是从服务器发送的 java 脚本

<html><body>"+ "<script type=\"text/javascript\">parent.handleResponse('error',securityLoginStatus.getLoginFailedException());</script>"+ "</body></html>")

我已经在父窗口中定义了一个方法,即handle-response,但我在浏览器中出现以下错误

Permission denied to access property 'handleResponse'

我什至尝试使用parent.wwindow.handleResponse,但得到了同样的错误。 有什么方法可以从 Iframe 与父窗口通信?

【问题讨论】:

  • 我认为parent.wwindow 也是一个错字。
  • 是的,这只是一个错字:) 在实际代码中是parent
  • 试试window.top.handleResponse
  • 我使用 jquery 做了类似的事情,我通常使用top.window。我通常将它用作选择器,因此可能需要对其进行调整。
  • @Furqan:我不确定这种方法。很抱歉没有意识到这一点。我更像是 UI 的服务器端人员 :(

标签: javascript jquery iframe same-origin-policy


【解决方案1】:

正如你之前所说,除非 html 来源和命运都在 http://localhost:9002 域下,否则无法避免跨来源权限被拒绝。

为方便起见,我建议使用带有 javascript/json/jsonp 文档的 http 通信。 你可以尝试 jQuery 类似的东西:

<script type="text/javascript">
function sendPost () {
    $.ajax({
      type: 'POST',
      url: 'https://localhost:9002/myApp/springSecurity/login',
      data: $("#guestFrame").serialize(),
      error: function(data, status) {
        // alert('Error ' + status);
      }
    });
}
function handleResponse(obj) {
    if (obj.type==="error") {
        alert("Error: " + obj.mssg);
    }
}
</script>

<form ...>
 ...
 <input type="submit" value="send" onclick="sendPost();return(false)"/>
</form>

并且为了避免 CORS 限制,https://localhost:9002/myApp/springSecurity/login html 响应必须是 javascript 代码并包含 以下标题:

<% 
response.setHeader("Content-type", "application/x-javascript");
response.setHeader("Access-Control-Allow-Origin", "*");
%>

Javascript 示例响应将能够调用其父调用者的“handleResponse”:

handleResponse({'type':'error', 'mssg': 'your_login_failed_exception'});

【讨论】:

    【解决方案2】:

    也可以使用http://easyxdm.net/wp/等框架进行跨域调用

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 2011-01-10
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 2014-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多