为了账号安全,请及时绑定邮箱和手机立即绑定

PHP - 提交表单而不退出页面

PHP - 提交表单而不退出页面

料青山看我应如是 2024-01-03 17:34:42
在数据输入表单中,我希望当单击“提交”按钮时,它不会离开表单所在的页面。提交论坛后,会向用户显示一个弹出窗口,其中包含表单已发送的信息!在搜索中,我知道AJAX存在,但我不知道如何完全实现它。我是 PHP 新手,我希望有人能帮助我!对不起我的英语!HTML:<form action="php/newsletter.php" method="post" class="formulario">                <input type="text" name="email" placeholder="Email" required>              </div>            <div class="ss-item-required" style="text-align:center;">              <button type="submit" class="site-btn">Send</button>            </div>          </form>PHP:  <?php$servername = "localhost";$username = "root";$password = "";$dbname = "DB";$conexao = new mysqli($servername, $username, $password, $dbname);if ($conexao->connect_error) {    die("Erro na conexão: " . $conexao->connect_error);}if (!$conexao) {    die("Erro de ligação: " . mysqli_connect_error());}$sql = "INSERT INTO newsletter (email) VALUES ('email')";if (mysqli_query($conexao, $sql)) {    echo '<div id="form-submit-alert">Submitted!</div>'; } else {    echo "Erro: " . $sql . "<br>" . mysqli_error($conexao);}?>
查看完整描述

4 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

使用 Ajax,您可以调用 html 请求并使用返回代码执行某些操作。

例如,您可以拦截提交表单并就地创建 ajax 请求。这个ajax请求调用你的php函数,并获取结果来显示/更新页面中的一些数据,而无需重新加载所有html。

https://api.jquery.com/jquery.ajax/

 <head>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

 </head> 



<form action="php/newsletter.php" method="post" class="formulario">

     <input type="text" name="email" placeholder="Email" required>

     <div class="ss-item-required" style="text-align:center;">

          <button type="submit" class="site-btn">Send</button>

     </div>

</form>


<script>

jQuery(document).ready(function() {


    let form = $('body').find('form');

    $(form).submit(function(e){


            e.preventDefault();

            e.stopPropagation();

            var formData = new FormData($(form)[0]); // serialize form data


            $.ajax({

               type:"POST",

               url:$(form).attr('action'), // use your form action as ajax url

               data:formData,

               contentType: false,

               processData: false,


               success: function(response){


                // test if response is json array or html content

                var is_JSON = true;

                try{ var json = $.parseJSON(response);

                }catch(err){ is_JSON = false; } 


                if(is_JSON){ // json resonse : if your php return json (for handle error )

                    console.log('response is JSON')

                }else{

                    // response is your html of php return

                    console.log('response is not JSON')

                    console.log(response)

                }

            }

        });

        });

});

</script>

未经测试,但这应该有效。



查看完整回答
反对 回复 2024-01-03
?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

我会使用 JavaScript 来实现这种方法。


假设您的表单具有 id my-form;您的 JavaScript 需要阻止表单正常提交并接管该过程本身。


let form = document.getElementById("my-form"); // find the form

form.addEventListener("submit", function (event){ // react to the submit try

     event.preventDefault(); // prevent the sending at this point


     let data = new FormData(form); // collect data, as we want to send it later

     // We'll use an XMLHttpRequest, which basically means we send a normal web

     // request from JavaScript and can interpret the answer afterwards

     let xhr = new XMLHttpRequest();

     xhr.onreadystatechange = function() {

         // here we can define code to be executed when the request is running

         if(this.readyState == 4 && this.status == 200){

             // we know the request has been successfull

             window.alert("Data sent!"); // Popup

         }

     };


     // finally we need to execute the xhr

     let method = form.getAttribute("method").toUpperCase();

     let url = form.getAttribute("action"); // reuse from form


     xhr.open(method, url, true);

     xhr.send(data);

});

这种方法的好处是它完全在后台运行,即用户可以在请求运行时继续使用该站点,并且不涉及另一个库。


查看完整回答
反对 回复 2024-01-03
?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

那么您所说的是在提交按钮之后您实际上会发送到后端页面吗?我要做的是(在后端页面)当代码执行时,简单地放置一个 php 语句:

location:('index.html');

这样您将立即返回到您提交表单的页面


查看完整回答
反对 回复 2024-01-03
?
烙印99

TA贡献1829条经验 获得超13个赞

当您提交表单时,我们将设置一个 $result var 来保存结果。


然后我们再次使用查询url参数重定向到index.php ?result=success


然后我们确保 if 已设置 (isset()) 并比较该值以显示正确的消息。


所以假设表单位于 /index.php 中


<?php

if(isset($_GET['result') && $_GET['result') == "success") {

echo '<div id="form-submit-alert">Submitted success!</div>';

} else {

echo '<div id="form-submit-alert">Submitted error!</div>';

}

?>

<form action="php/newsletter.php" method="post" class="formulario">

  <div>

    <input type="text" name="email" placeholder="Email" required>

  </div>

  <div class="ss-item-required" style="text-align:center;">

    <button type="submit" class="site-btn">Send</button>

  </div>

</form>

// php/newsletter.php


<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "DB";

$conexao = new mysqli($servername, $username, $password, $dbname);


// Init result

$result = "error";


if ($conexao->connect_error) {

    die("Erro na conexão: " . $conexao->connect_error);

}

if (!$conexao) {

    die("Erro de ligação: " . mysqli_connect_error());

}

$sql = "INSERT INTO newsletter (email) VALUES ('email')";

if (mysqli_query($conexao, $sql)) {


    // if the result is OK

    $result = "success";

} else {

    echo "Erro: " . $sql . "<br>" . mysqli_error($conexao);

}



// Redirect to initial page with the query url param

header("Location: /index.php?result={$result}");

?>


查看完整回答
反对 回复 2024-01-03
  • 4 回答
  • 0 关注
  • 72 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信