繁体   English   中英

用户取消离开后如何在不刷新的情况下停留在同一页面上?

[英]How to stay on the same page without refreshing after the user cancels leaving?

我有一个网页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> 

我有两个问题:

  1. 当用户确认他想离开时,代码不会重定向到Leave.php,但是会刷新当前页面。 我该如何解决?
  2. 当用户在确认框中选择“取消”时,将重新加载页面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> 

如果必须提交按钮,则每个按钮都将提交您的表单。 因此,在重定向到"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> 

这是一个工作版本。 我认为问题在于return语句“ return Confirm()”:

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM