如何从<form target =“IFrame”> </form>获得响应

时间:2011-10-03 05:47:17

标签: java javascript jquery servlets

有一个简单的网页发送请求,处理&amp;由servlet类操纵并发回响应text。虽然我希望ajax类型在客户端处理请求,这就是为什么我将响应目标提供给不可见的iframe。 *但我想在iframe获得回复之后在页面上打印success *

<html> <body>
<form action="test" method="post" target="IFrame"> /*response target is iframe*/
       <input type="text" name="logic" />
       <input type="submit" value="Submit" />
</form>

<iframe name="IFrame" style="width:0; height:0"> </iframe>

</body>  </html>

我认为可以使用javascriptjquery来完成,如果您有任何想法,请指教我。

2 个答案:

答案 0 :(得分:1)

在iframe中加载的页面中,您需要调用父函数。

<!-- This is the Parent.  Call it JSTest1.html -->
<html>
<head>
</head>
<body>
<script type="text/javascript">
    function parentAlert() {
        alert('hey there from the parent');
    }
</script>
I'm the parent
<iframe src="/JSTest2.html"></iframe>
</body>

<!-- this is the iframe html loaded.  Call it JSTest2.html-->
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
    $(document).ready( function() {
        window.parent.parentAlert();
    });
</script>
In the Iframe.
</body>

答案 1 :(得分:1)

从Iframe向父窗口页面发送消息:

<script type="text/javascript">
  $(document).ready( function() {
    //Message part is two parts Event name and Data you want to send
    // Example message = "my_action,my_data"
    message = "my_action,my_data" 
    parent.postMessage(message, "*");
  });
</script>

在父窗口,您可以执行以下操作来收听此消息并捕获它:

var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

eventer(messageEvent,function(e) {
  // Youe message which you send is captured here in e.data will split it on ',' to get the event and the data  
  message = e.data.split(',')[0]
  value = e.data.split(',')[1]
  if ( message === "my_action" ) {
      myParentFunction(value)
  }     
},false);