2016-07-25 91 views
0

我有一个简单的POST脚本,用于发送电子邮件的PHP,但是当我单击提交按钮时,它会执行,然后进入脚本目录(例如:localhost/sendMail/test.php)。是否可以发布警告框,然后留在页面上而不是转到脚本,然后重定向回到提交页面?执行脚本后PHP取消重定向

这是我的脚本。

<?php 
$subject = 'Your website: Contact'; // Subject of your email 
$to = 'myemail'; // Enter recipient's E-mail address 
$emailTo = $_REQUEST['email']; 

$headers = "MIME-Version: 1.1"; 
$headers .= "Content-type: text/html; charset=iso-8859-1"; 
$headers .= "From: " . $emailTo . "\r\n"; // Sender's E-mail 
$headers .= "Return-Path:". $emailTo; 

$body = 'You have received a new inquiry!' . "\n\n"; 
$body .= 'Name: ' . $_REQUEST['name'] . "\n"; 
$body .= 'Email: ' . $_REQUEST['email'] . "\n"; 
$body .= 'Phone: ' . $_REQUEST['phone'] . "\n\n"; 
$body .= 'Message: ' . $_REQUEST['message']; 

if($_REQUEST['name'] != "" && $_REQUEST['email'] != "" && $_REQUEST['phone'] != "" && $_REQUEST['message'] != "") 
{ 
    if (@mail($to, $subject, $body, $headers)) 
    { 
     // Transfer the value 'sent' to ajax function for showing success message. 
     echo 'sents'; 
    } 
    else 
    { 
     // Transfer the value 'failed' to ajax function for showing error message. 
     echo 'failed'; 
    } 
} 
else 
{ 
    $message = "Invalid fields!"; 
    echo "<script type='text/javascript'>alert('$message');</script>"; 
    //header("Location: http://localhost/abtek/contact.html"); 
    exit; 
} 
?> 

所以在执行警戒时,是否有可能从去到脚本,并在页面上,而不是停留,直到场都是有效的提交停止吗?以及提交时再次显示警报并保留在页面上而不是执行一系列重定向。

任何帮助将不胜感激。

+0

使用AJAX。去谷歌上查询! – pioneer

+0

并根据您使用的框架,您可能需要使用exit($ message)而不是返回$ message。我知道我必须处理的主要框架,我知道。 – VikingBlooded

回答

0

您可以使用jQuery,像这样:

$('#my-submit').on('click', function(e){ 
    e.preventDefault(); // prevents regular form submission 
    $.ajax({ 
     url: 'localhost/sendMail/test.php', 
     data: $('form').serialize(), 
     success: function(result){ 
      alert('Message: ' + result); 
     }, 
     error: function(err){ 
      alert(err) 
     } 
    }) 
}); 

在你的PHP你应该只是做echo $message;以更好地处理错误。 阅读关于jQuery/AJAX的所有信息,因为有很多重要的选项可以使用,比如使用JSON。