表单提交后需实现两项操作:新标签打开invoice.php并返回首页
表单提交后实现双标签页操作的解决方案
当前表单已经能在提交后打开新标签页加载invoice.php,但原标签页无法自动返回首页,下面提供两种实用解决方法:
方法一:纯前端JS拦截实现
修改表单代码,通过JavaScript监听提交事件,控制原页面跳转:
<form id="myForm" method="POST" action="invoice.php" target="_blank"> <label>Name</label><input type="text" name="name1"> <label>Age</label><input type="text" name="age"> <label>Gender</label><input type="text" name="gender"> <label>Height</label><input type="text" name="height"> <label>Education</label><input type="text" name="edu"> <input type="submit" name="submit" id="submit" value="Submit" class="btn btn-success submit_btn invoice-save-btm"> </form> <script> document.getElementById('myForm').addEventListener('submit', function() { // 延迟跳转原页面,确保表单数据发送完成 setTimeout(() => { window.location.href = '/'; // 替换成你的首页地址 }, 500); }); </script>
延迟500毫秒是为了避免原页面跳转过快导致表单提交中断,可根据实际情况调整时长。
方法二:后端配合实现(更稳定)
如果担心前端延迟的不确定性,让invoice.php处理完数据后主动控制原页面跳转:
保持原表单不变,在invoice.php处理完业务逻辑后添加以下代码:
<?php // 这里写你的表单数据处理逻辑(比如存数据库、生成发票等) // 处理完成后输出脚本 ?> <script> // 控制原页面跳转到首页 window.opener.location.href = '/'; // 如果不需要保留新标签页,可加这行关闭它:window.close(); </script>
这种方法只有在后端成功处理完数据后才会触发跳转,稳定性更高。
内容的提问来源于stack exchange,提问作者Moon
相关产品推荐
相关产品推荐

