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

在数据输入表单中,我希望当单击“提交”按钮时,它不会离开表单所在的页面。


提交论坛后,会向用户显示一个弹出窗口,其中包含表单已发送的信息!


在搜索中,我知道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);

}

?>


料青山看我应如是
浏览 147回答 4
4回答

皈依舞

使用 Ajax,您可以调用 html 请求并使用返回代码执行某些操作。例如,您可以拦截提交表单并就地创建 ajax 请求。这个ajax请求调用你的php函数,并获取结果来显示/更新页面中的一些数据,而无需重新加载所有html。https://api.jquery.com/jquery.ajax/&nbsp;<head>&nbsp; &nbsp; &nbsp; <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>&nbsp;</head>&nbsp;<form action="php/newsletter.php" method="post" class="formulario">&nbsp; &nbsp; &nbsp;<input type="text" name="email" placeholder="Email" required>&nbsp; &nbsp; &nbsp;<div class="ss-item-required" style="text-align:center;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button type="submit" class="site-btn">Send</button>&nbsp; &nbsp; &nbsp;</div></form><script>jQuery(document).ready(function() {&nbsp; &nbsp; let form = $('body').find('form');&nbsp; &nbsp; $(form).submit(function(e){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.stopPropagation();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var formData = new FormData($(form)[0]); // serialize form data&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;type:"POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;url:$(form).attr('action'), // use your form action as ajax url&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;data:formData,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;contentType: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;processData: false,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;success: function(response){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // test if response is json array or html content&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var is_JSON = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try{ var json = $.parseJSON(response);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }catch(err){ is_JSON = false; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(is_JSON){ // json resonse : if your php return json (for handle error )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('response is JSON')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // response is your html of php return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('response is not JSON')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(response)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; });});</script>未经测试,但这应该有效。

汪汪一只猫

我会使用 JavaScript 来实现这种方法。假设您的表单具有 id my-form;您的 JavaScript 需要阻止表单正常提交并接管该过程本身。let form = document.getElementById("my-form"); // find the formform.addEventListener("submit", function (event){ // react to the submit try&nbsp; &nbsp; &nbsp;event.preventDefault(); // prevent the sending at this point&nbsp; &nbsp; &nbsp;let data = new FormData(form); // collect data, as we want to send it later&nbsp; &nbsp; &nbsp;// We'll use an XMLHttpRequest, which basically means we send a normal web&nbsp; &nbsp; &nbsp;// request from JavaScript and can interpret the answer afterwards&nbsp; &nbsp; &nbsp;let xhr = new XMLHttpRequest();&nbsp; &nbsp; &nbsp;xhr.onreadystatechange = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// here we can define code to be executed when the request is running&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(this.readyState == 4 && this.status == 200){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// we know the request has been successfull&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;window.alert("Data sent!"); // Popup&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;};&nbsp; &nbsp; &nbsp;// finally we need to execute the xhr&nbsp; &nbsp; &nbsp;let method = form.getAttribute("method").toUpperCase();&nbsp; &nbsp; &nbsp;let url = form.getAttribute("action"); // reuse from form&nbsp; &nbsp; &nbsp;xhr.open(method, url, true);&nbsp; &nbsp; &nbsp;xhr.send(data);});这种方法的好处是它完全在后台运行,即用户可以在请求运行时继续使用该站点,并且不涉及另一个库。

翻过高山走不出你

那么您所说的是在提交按钮之后您实际上会发送到后端页面吗?我要做的是(在后端页面)当代码执行时,简单地放置一个 php 语句:location:('index.html');这样您将立即返回到您提交表单的页面

烙印99

当您提交表单时,我们将设置一个 $result var 来保存结果。然后我们再次使用查询url参数重定向到index.php ?result=success然后我们确保 if 已设置 (isset()) 并比较该值以显示正确的消息。所以假设表单位于 /index.php 中<?phpif(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">&nbsp; <div>&nbsp; &nbsp; <input type="text" name="email" placeholder="Email" required>&nbsp; </div>&nbsp; <div class="ss-item-required" style="text-align:center;">&nbsp; &nbsp; <button type="submit" class="site-btn">Send</button>&nbsp; </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) {&nbsp; &nbsp; die("Erro na conexão: " . $conexao->connect_error);}if (!$conexao) {&nbsp; &nbsp; die("Erro de ligação: " . mysqli_connect_error());}$sql = "INSERT INTO newsletter (email) VALUES ('email')";if (mysqli_query($conexao, $sql)) {&nbsp; &nbsp; // if the result is OK&nbsp; &nbsp; $result = "success";} else {&nbsp; &nbsp; echo "Erro: " . $sql . "<br>" . mysqli_error($conexao);}// Redirect to initial page with the query url paramheader("Location: /index.php?result={$result}");?>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5