亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 217 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號