将表单设置为将数据发送到同一页面,并让您的脚本监听提交。就像是:
联系人.php
<?php
// Check if form was previously submitted
if(isset($_POST['myFormSubmitted'])) {
// Do your form processing here and set the response
$response = 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
<!-- HTML here -->
<?php
if (isset($response)) { // If a response was set, print it out
echo $response;
}
?>
<form method="POST" action="contact.php">
<!-- Your inputs go here -->
<input type="submit" name="myFormSubmitted" value="Submit">
</form>
<!-- More HTML here -->
更新
考虑到提供的额外信息,我个人会通过 AJAX 使用 jQuery 来完成。首先,为结果设置表单和容器:
HTML
<form id="myForm" method="POST" action="contact.php">
<input type="text" id="name" name="name">
<input type="text" id="email" name="email">
<input type="text" id="message" name="message">
<input type="submit" name="myFormSubmitted" value="Submit">
</form>
<div id="formResponse" style="display: none;"></div>
然后设置处理提交数据并输出响应的 php 脚本。
PHP (contact.php)
<?php
if(isset($_POST['myFormSubmitted'])) {
// Do your form processing here and set the response
echo 'Thank you for your Email. We will get in touch with you very soon.';
}
?>
最后,jQuery 脚本将在不离开页面的情况下提交您的表单并将结果插入到您的结果容器中(具有漂亮而简单的淡入效果)。
jQuery
$("#myForm").submit(function() {
$.post('contact.php', {name: $('#name').val(), email: $('#email').val(), message: $('#message').val(), myFormSubmitted: 'yes'}, function(data) {
$("#formResponse").html(data).fadeIn('100');
$('#name, #email, #message').val(''); /* Clear the inputs */
}, 'text');
return false;
});
希望这可以帮助 !