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

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

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

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

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

表单看起来像这样(已简化),响应已准备就绪,我将数据提交到同一页面上的 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>

现在,我收到答复并处理它。 return 是 Json,数组 $response["success"] 为真或假。如果失败,它还包含一个错误数组。 这是我在处理完 post 数据后此刻的响应处理:

$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 中回显一个简单的 "thank you",但我想调用 Javascript(bootstrap 模态)以获得更好的响应。或者通常在页面而不是 iframe 中做一些事情。

我不确定如何从这个地方"go back"/"talk"到带有表单的页面。

如何使用表单在父页面中调用下面的 javascript 函数?或者实际上还有其他功能吗?

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

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

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

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

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

添加到submit.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>"; 
}