2009-10-22 44 views
6

我不用PHP代碼,但我有這種形式,我脫離了網絡,它的工作很棒:如何顯示來自PHP的JavaScript警報?

我想要做的是以某種方式在這裏添加一些代碼,可以啓動一個JS腳本,簡單的警示框,說「謝謝你的表格被提交」。表單被這個mailer.php文件接收後。

<?php 
if(isset($_POST['submit'])) { 

$to = "[email protected]"; 
$subject = "Form Tutorial"; 
$name_field = $_POST['name']; 
$email_field = $_POST['email']; 
$message = $_POST['message']; 

$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message"; 

echo "Data has been submitted to $to!"; 
mail($to, $subject, $body); 

} else { 

echo "blarg!"; 

} 
?> 
+2

LOL @描述性錯誤消息......畢竟它是* PHP。 – 2009-10-22 22:57:49

+1

注意:僅僅因爲你可以使用警告框並不意味着你應該。 – 2009-10-22 23:22:59

回答

19

echo "Data has been submitted to $to!"; 

只是

echo '<script type="text/javascript">alert("Data has been submitted to ' . $to . '");</script>'; 
3

您可以echo的Javascript在你的PHP中的<script></script>塊。瀏覽器會執行它。

因此,例如:代替

<?php 
    echo "<script language='javascript'>alert('thanks!');</script>"; 
?> 
2

你只需要輸出HTML/JS。事情是這樣的:

<?php 
    if(isset($_POST['submit'])) { 
     $to = "[email protected]"; 
     $subject = "Form Tutorial"; 
     $name_field = $_POST['name']; 
     $email_field = $_POST['email']; 
     $message = $_POST['message']; 

     $body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message"; 

     mail($to, $subject, $body); 
     echo "<script type=\"text/javascript\">alert('Thank you form is submitted');</script>"; 
    } else { 
     echo "blarg!"; 
    } 
?> 

或者:

<?php 
    if(isset($_POST['submit'])) { 
     $to = "[email protected]"; 
     $subject = "Form Tutorial"; 
     $name_field = $_POST['name']; 
     $email_field = $_POST['email']; 
     $message = $_POST['message']; 

     $body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message"; 

     mail($to, $subject, $body); 
?> 
    <script type="text/javascript">alert('Thank you form is submitted.');</script> 
<?php 
    } else { 
     echo "blarg!"; 
    } 
?> 

然而,這聽起來像你也許不希望有提交表單,並給予用戶確認的頁面重載。爲此,您需要通過AJAX提交表單。我建議看看JQuery。它makes this easy