【问题标题】:How to avoid page reload in php form submission如何避免在php表单提交中重新加载页面
【发布时间】:2014-06-05 11:02:45
【问题描述】:

我目前在我的 html 页面中使用 php,并且在同一页面中有一个在表单提交时执行的操作。目前整个表单被重新加载,而我希望 php 操作在后台运行而不重新加载。我该怎么做。单击提交按钮后,我还想清除文本框。以下是我目前使用的代码

<html>
<head>
</head>

<body>
    <form action="index.php" method="post"  role="form">
        <input type="email" placeholder="Enter email"  name="email_address">
        <button class="btn btn-primary custom-button red-btn">Sign Up</button>
    </form>

<?php



if(isset($_POST['email_address'])  !(trim($_POST['email_address']) == ''))

// do some action
}

?>
</body>

</html>

注意:以下代码对我有用

<script type="text/javascript">
    $('#contactForm').submit(function () {
       $.post("mailer.php",$("#contactForm").serialize(), function(data){
       });
        return false;
    });
</script>

【问题讨论】:

  • 您应该将用户重定向到其他页面,例如谢谢..

标签: javascript php jquery html forms


【解决方案1】:

您需要为此使用 AJAX,无需重新加载。或者,如果您想在不干扰页面的情况下进行操作,则需要设置target

使用 AJAX

$("form").submit(function(){
  $.post($(this).attr("action"), $(this).serialize());
  return false;
});

使用target

<form action="index.php" method="post" role="form" target="_blank">

【讨论】:

  • 我会谨慎使用 return false; - 通常更喜欢 e.preventDefault() 因为返回 false 也会停止事件传播,如果您依赖事件冒泡可能会影响其他功能。
  • $('#contactForm').submit(function () { $.post("mailer.php",$("#contactForm").serialize(), function(data){ } ); 返回 false; });为我工作
【解决方案2】:

使用 ajax

HTML

<html>
<head>
</head>

<body>
    <form id="myform"><!--changge-->
        <input type="email" placeholder="Enter email"  name="email_address">
        <button class="btn btn-primary custom-button red-btn" id="signup">Sign Up</button>
    </form>
</body>
</html>
<script>
    $(document).ready(function()
    {
        $('#signup').click(function()
    {
         $.ajax({
          url:'index.php',
          method:'post',
          data : $('#myform').serialize(),
          success:function()
         {
         } 

    )};
    );
    });
</script>

【讨论】:

  • 这给了我语法错误 $.post("mailer.php",$("#contactForm").serialize(), function(data){ });
【解决方案3】:

你可以试试这个

<html>
<head>
</head>

<body>
    <form id="myform" action="index.php"><!--changge-->
        <input type="email" placeholder="Enter email"  name="email_address">
        <button class="btn btn-primary custom-button red-btn" id="signup">
         Sign Up</button>
    </form>

<script>
$(document).ready(function(){
    $('#signup').click(function(){
        $.post($(this).attr("action"), $("#myform").serialize(),function(response){
            alert(response) // you can get the success response return by php after submission success
        });
    )};
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2014-04-30
    • 2013-01-05
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    相关资源
    最近更新 更多