我有一个网页test.php:
表格
“提交”按钮,将答案发送到表单;
一个“离开”按钮,允许用户离开页面(并转到'leave.php')而不填写表格;
控制器,当用户点击提交时控制数据,并在一切正确时重定向到其他地方。
我希望用户在重定向之前确认他想要离开。到目前为止,这是我的代码:
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>
我有两个问题:
答案 0 :(得分:2)
您可以使用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>
答案 1 :(得分:1)
如果您必须提交 - 按钮,他们每个人都会提交您的表格。因此,重定向到"test.php"
和"leave.php"
之间存在冲突。在这种情况下,表单中的操作始终是第一个。
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="button" name="leave" value="Leave this page" onClick="return confirmation();">
</form>
答案 2 :(得分:1)
这是一个工作版本。我认为问题出在return语句中,&#34; return confirmation()&#34;:
<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="confirmation(); return false;">
</form>
<script>
function confirmation(e){
var result = confirm("Do you really want to leave this page?");
if (result) {
window.location = '/leave.php';
} else {
return FALSE;
}
}
</script>