从 iframe 中的 HTML 表单响应调用父页面


call onto the parent page from html-form response in iframe

我对处理表单输入和响应很陌生,我只是遇到了如何处理服务器响应的问题。

我有一个常规的输入表单,它调用一个php文件(submit.php(来处理提交。提交.php使用 curliframe 中执行。(信息:由于某些跨域问题,我无法使用 ajax 调用(

我想使用 javascript 引导模式在表单提交后显示感谢或错误消息。

表单看起来像这样(简化(,响应已准备好调用,并且我在同一页面上提交数据的 iframe:

<form action="submit.php" method="post" target="iframeAnswer" id="formTest">
  <input type="text" id="name" name="name" type="text" placeholder="your name here">
  <button class="submitMe" id="submitButton">Submit</button>
</form>
<div id="Modal" class="modal fade">
    <!-- ... some html for the thank you pop up ... -->
    <!-- ... display set to none for the moment ... -->
</div>
<iframe src="submit.php" name="iframeAnswer"></iframe>

现在,我收到答案并处理它。返回是 Json,一个数组$response["成功"],要么是真,要么是假。如果发生故障,它还包含一个错误数组。这是我在处理帖子数据后此刻的响应处理:

$responseJson = json_decode($response, true);
if ($responseJson["success"] == false) {
    for ($i = 0; $i < count($responseJson["errors"]); $i++) {
        // echo $responseJson["errors"][$i].' <br />';
        // HOW to process this answer other than echo
    }
}
else if ($responseJson["success"] == true) {
        // echo "Thank you!"; 
        // What to do here to reach parent frame
    }
}

的问题和我有点卡住的地方是:我现在可以在iframe中回声说一个简单的"谢谢",但我想调用Javascript(引导模态(来获得更好的回应。或者一般来说,在页面中而不是在 iframe 中执行一些操作。

我不确定如何从这个地方"返回"/"谈论"带有表单的页面。

例如,我如何使用表单在父页面中调用下面的 javascript 函数?或者实际上任何其他功能?

jQuery("#Modal").modal('show');

我觉得我快到了,但不知何故,我没有连接最后的点点滴滴。

好的,

现在经过一些研究和测试,最后似乎答案很简单。我正在回显一个调用父页面的 javascript 脚本。

告诉 javascript 在页面加载后执行很重要。否则,Javascript会尝试立即执行并返回错误,因为文档尚未完成。

您还需要在提交.php文件的头部(在 iframe 中(包含 jQuery 和引导程序,以便正确执行 jQuery。当然,如果您不使用引导模式,则不需要包含引导程序。

添加到提交.php的标题:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="../bootstrap/js/bootstrap.min.js"></script>

以下是我在 submit.php 文件中的服务器响应处理中添加的内容:

if ($responseJson["success"] == true) {
    echo "<script> $(document).ready( function () {";
    // wait for document to load, so the JS doesnt try to execute while document is written
    echo "$('#Modal', window.parent.document).modal('show');";
    echo "}); </script>";            
    }
}
if ($responseJson["success"] == false) {
    echo "<script> $(document).ready( function () {";
    for ($i = 0; $i < count($responseJson["errors"]); $i++) {
        // Do something here
        // output with Javascript like in the success handling
    }
    echo "}); </script>"; 
}