您正在使用JQuery函式庫,但是您正在使用原生JavaScript指令來處理按鈕和submit()。要嘛您全部使用Pure JS,要嘛全部使用JQuery。
下面的程式碼僅使用JQuery。此外,我用一個按鈕替換了submit。
。
最後,按鈕不會以POST方式傳遞,所以如果您需要進行測試,請在輸入欄位上進行。
下面是一個包含我剛剛提到的元素的程式碼,應該可以幫助您。
<? // 當表單提交時處理表單數(shù)據(jù) if ($_SERVER["REQUEST_METHOD"] == "POST") { if(isset($_POST['username'])) { $uname=$_POST['username']; header('Location: success.php'); } } ?> <!DOCTYPE html> <html> <head> <title>My Form</title> </head> <body> <form id="your_form_id" action="test4.php" method="post"> <p><label>Username</label> <input id="username" type="text" name="username" value="" autofocus/></p> <input type="button" id="submit-button" name="submit-button" value="Login" /> </form> <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $("#submit-button").on("click", function(e){ $('#submit-button').prop('disabled',true); $('#submit-button').val('Processing, please wait...'); $('#your_form_id').submit(); }); </script> </body> </html>
為了實現(xiàn)這一點,可以使用以下原則:
test-a.php:
<!DOCTYPE html> <html> <head> <title>Ajax example with Page loader</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style> /*CSS for Page loader*/ #loader { display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 9999; } </style> <script> $(document).ready(function() { $('#myForm').submit(function(e) { e.preventDefault(); // 阻止元素的默認操作 $('#submitButton').prop('disabled', true); // 禁用id為submitButton的按鈕 $('#loader').show(); // 顯示“頁面加載器” // 發(fā)送AJAX請求 $.ajax({ url: 'test-b.php', //處理PHP文件的路徑 type: 'POST', data: $(this).serialize(), success: function(response) { // 將響應保存到會話變量中 sessionStorage.setItem('response', response); // 轉(zhuǎn)到“test-c.php” window.location.href = 'test-c.php'; } }); }); }); </script> </head> <body> <form id="myForm" method="POST"> <label for="name">Name:</label> <input type="text" name="name" id="name" required><br> <label for="email">Email:</label> <input type="email" name="email" id="email" required><br> <input type="submit" id="submitButton" value="Submit"> </form> <div id="loader"> This is page loader, please wait... </div> </body> </html>
test-b.php:
<?php session_start(); $name = $_POST['name']; $email = $_POST['email']; // 在這里可以使用$name和$email進行進一步處理或保存到數(shù)據(jù)庫 // 打印響應數(shù)據(jù)的示例 $response = "The following data has been received:<br>"; $response .= "Name: " . $name . "<br>"; $response .= "Email: " . $email . "<br>"; // 將響應保存到會話變量中 $_SESSION['response'] = $response; // 完成本文件的工作 exit; ?>
test-c.php:
<!DOCTYPE html> <html> <head> <title>Success</title> <style> h1 { color: green; } </style> </head> <body> <h1>Process file response:</h1> <?php session_start(); if (isset($_SESSION['response'])) { $response = $_SESSION['response']; echo $response; unset($_SESSION['response']); // 取消設(shè)置會話變量 } else { echo "No data to show."; } ?> </body> </html>