我有一个网页 test.php,其中包含:
表单
“提交”按钮,用于将答案发送到表单;
“离开”按钮允许用户离开页面(并转到“leave.php”)而不填写表单;
一个 Controller ,用于在用户单击“提交”时控制数据,并在一切正确时重定向到其他地方。
我希望用户在重定向之前确认他想要离开。这是到目前为止我的代码:
function confirmation(){
var result = confirm("Do you really want to leave this page?");
if(result){
window.location = 'leave.php';
}
else{
return FALSE;
}
}
<form method="post" action="test.php">
<input type="text" name="answer" id="answer" placeholder="Type your answer here">
<input type="submit" name="submit_answer" value="Submit your answer">
<input type="submit" name="leave" value="Leave this page" onClick="return confirmation();">
</form>
我有两个问题:
- 当用户确认他想要离开时,代码不会重定向到leave.php,但会刷新当前页面。我该如何解决这个问题?
- 当用户在确认框中选择“取消”时,页面 test.php 会重新加载,并且数据会丢失:也就是说,即使用户在单击“离开”之前写了一些内容,文本框也是空的。有没有办法避免这种情况?
最佳答案
您可以使用 JavaScript 提交表单。首先,将两个按钮更改为 type="button"
。使用 type="submit"
提交导致错误的按钮。然后编写一个简单的函数来提交表单。
function confirmation(){
var result = confirm("Do you really want to leave this page?");
if(result){
window.location = 'leave.php';
}
else{
return FALSE;
}
}
function submitForm(){
var form = document.getElementById('form');
form.submit();
}
<form id="form" method="post" action="test.php">
<input type="text" name="answer" id="answer" placeholder="Type your answer here">
<input type="button" name="submit_answer" value="Submit your answer" onClick="submitForm()">
<input type="button" name="leave" value="Leave this page" onClick="return confirmation();">
</form>
关于javascript - 用户取消离开后如何保持在同一页面而不刷新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48832051/