在Web开发中,表单提交后关闭JavaScript弹出窗口并更新父页面是一个常见的需求。以下是实现这一功能的基础概念和相关步骤:
window.open()
方法创建的新窗口。首先,你需要创建一个弹出窗口并在其中放置表单。当用户提交表单时,可以通过JavaScript处理表单提交并关闭弹出窗口。
<!-- 父页面 (parent.html) -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Parent Page</title>
<script>
function openPopup() {
var popup = window.open('popup.html', 'popupWindow', 'width=400,height=300');
}
function updateParent() {
document.getElementById('result').innerText = 'Form submitted successfully!';
}
</script>
</head>
<body>
<button onclick="openPopup()">Open Popup</button>
<div id="result"></div>
</body>
</html>
<!-- 弹出窗口 (popup.html) -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Popup Window</title>
<script>
function submitForm() {
var form = document.getElementById('myForm');
form.submit();
window.opener.updateParent();
window.close();
}
</script>
</head>
<body>
<form id="myForm" action="/submit" method="post">
<input type="text" name="data" placeholder="Enter data">
<button type="button" onclick="submitForm()">Submit</button>
</form>
</body>
</html>
parent.html
):openPopup()
函数打开弹出窗口。updateParent()
函数用于更新父页面中的结果显示区域。popup.html
):submitForm()
函数在表单提交后调用,首先提交表单数据到服务器,然后调用父页面的updateParent()
函数更新父页面内容,最后关闭弹出窗口。通过以上步骤和注意事项,可以实现表单提交后关闭弹出窗口并更新父页面的功能。