2013-03-20 67 views
0

有沒有一種快速簡單的方法可以讓這個form.php代碼在提交後關閉窗口而不是重定向?如果沒有辦法做到這一點,我可以處理重定向,但希望窗口剛剛關閉,因爲原始窗體正在新窗口中打開。下面的代碼:如何在成功提交時關閉PHP表單頁面?

<?php 
if (!empty($_POST)) { 

// Used for later to determine result 
$success = $error = false; 

// Object syntax looks better and is easier to use than arrays to me 
$post = new stdClass; 

// Usually there would be much more validation and filtering, but this 
// will work for now. 
foreach ($_POST as $key => $val) 
    $post->$key = trim(strip_tags($_POST[$key])); 

// Check for blank fields 
if (empty($post->First) OR empty($post->Last) OR empty($post->Email)) 
    $error = true; 

else { 

    // Get this directory, to include other files from 
    $dir = dirname(__FILE__); 


    // Get the contents of the HTML email into a variable for later 
    ob_start(); 
    require_once($dir.'/html.php'); 
    $html_message = ob_get_contents(); 
    ob_end_clean(); 

    // Load the SwiftMailer files 
    require_once($dir.'/swift/swift_required.php'); 

    $mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance  of SwiftMailer 

    $message = Swift_Message::newInstance() 
        ->setSubject('Hospitality Recycling Program Calculator Results') // Message subject 
        ->setTo(array('[email protected]', $post->Email =>$post-> First)) // Array of people to send 

        ->setFrom(array('[email protected]' => 'Clean the World')) // From: 
        ->setBody($html_message, 'text/html'); 






    // Send the email, and show user message 
    if ($mailer->send($message)) 
     $success = true; 
    else 
     $error = true; 

} 

} 
header("location: http://www.cleantheworld.org/newpartner.asp"); 
?> 
+0

您可以使用javascript,但這不是一個理想的解決方案。 – asprin 2013-03-20 14:24:51

+0

PHP無法關閉瀏覽器上的窗口。你需要JavaScript。並記住,JavaScript不能關閉一個窗口,它不是用JS打開的。 – 2013-03-20 14:24:52

+1

你將不得不使用javascript,但更好的解決方案是不爲你的窗體打開一個新窗口,而只是一個模式框,並使用Ajax提交表單。 – jeroen 2013-03-20 14:25:34

回答

0

我@jeroen同意,一個更好的解決辦法是使用AJAX,但你可以輸出重定向的頭JavaScript來關閉頁面。再次,我不建議這是一個很好的解決方案,但只要在用戶瀏覽器中啓用javascript,它就會工作。

<script type="text/javascript> 
    self.close(); 
</script>