设置表单以将数据发送到同一页面,并让您的脚本侦听提交。就像是:
联系方式.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 -->
UPDATE
考虑到所提供的额外信息,我个人会通过 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(联系.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;
});
希望这可以帮助 !