設置表單將數據發送到同一頁面,並讓腳本偵聽提交。喜歡的東西:
contact.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
考慮提供額外的信息,我會親自用jQuery做,通過AJAX。首先,設置您的形式和結果的容器:
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;
});
希望這有助於!
@FreekOne我認爲您的解決方案非常接近我想要什麼,但我需要一些時間來弄清楚如何使用它。這是一個完全不同的方法。現在我正在使用這樣的文本佔位符的郵件主體:
$ mailbody = file_get_contents('mailbody.txt'); ('name ###',htmlspecialchars($ name),$ mailbody); \t $ mailbody = str_replace('### EMAIL ###',$ email,$ mailbody); ('### NACHRICHT ###',htmlspecialchars($ nachricht),$ mailbody);
我不再需要這個了 - 對嗎?但是,如果JavaScript被禁用會發生什麼? – markimark 2010-10-03 15:02:20
爲什麼我不能在該評論部分使用任何代碼,對此抱歉........希望你瞭解反正..... – markimark 2010-10-03 15:03:08
不,你仍然需要這個,你也必須定義'$ name','$ email','$ nachricht'。如果JS被禁用,表單仍然會被正確提交,儘管用戶只會看到一個帶有「謝謝」信息的白頁。 – 2010-10-03 15:07:05