0

您好我正在尝试从数据作为电子邮件发送。我正在使用 PHP mail() 发送电子邮件并使用 Ajax 提交数据以避免页面重新加载。提交表单时未发送电子邮件。我究竟做错了什么?代码有点像这样。

阿贾克斯:

$('#submit').click(function(){

    $.ajax({
        url: test.php,
        type:'POST',
        success: function(msg){
                alert('Email Sent');
            }                   
        });
    });

HTML 表单:

<table width="400" border="0" cellspacing="2" cellpadding="0"> 
   <tr> 
        <td>*Your name:</td> 
        <td><input name="name" type="text" id="name" size="32"></td> 
   </tr> 
   <tr> 
        <td class="bodytext">*Email address:</td> 
        <td><input name="email" type="text" id="email" size="32"></td> 
   </tr> 
   <tr> 
        <td class="bodytext"> </td> 
        <td align="left" valign="top"><input type="submit" name="Submit" id="submit" value="Send"></td> 
   </tr> 
</table> 

php:

<?php 
if ($_POST["email"]<>'') { 
    $ToEmail = 'somugus@gmail.com'; 
    $EmailSubject = 'Fusio Dose customer info'; 
    //$mailheader = "From: ".$_POST["email"]."\r\n"; 
    //$mailheader .= "Reply-To: ".$_POST["email"]."\r\n"; 
    //$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
    $MESSAGE_BODY = "Name: ".$_POST["name"]."\r\n"; 
    $MESSAGE_BODY .= "Email: ".$_POST["email"]."\r\n"; 
    $MESSAGE_BODY .= "Primary: ".$_POST["primary"]."\r\n";
    $MESSAGE_BODY .= "Sedcondary: ".$_POST["secondary"]."\r\n";
    //$MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"]).""; 
    mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure"); 
?> 

工作示例在这里

http://soumghosh.com/otherProjects/Kemail/emailTest1.html

4

3 回答 3

2

您可以序列化表单并将其提交到您的 PHP 页面。试试这个,它不会提交页面:

$('#contact_form').submit(function() {  
    alert($(this).serialize()); // check to show that all form data is being submitted
    $.post("test.php",$(this).serialize(),function(data){
        alert(data); //check to show that the email sent successfully                        
    });
    return false; // return false to stop the page submitting. You could have the form action set to the same PHP page so if people dont have JS on they can still use the form
});
于 2013-04-02T02:42:31.570 回答
0

将您的函数调用更改为此

$('#submit').submit(function(e) {

  e.preventDefault();
  //The rest of your code. 

   $.ajax({
    url: test.php,
    type:'POST',
    data: { name: $("#name").val(), email: $("#email").val() } // and so on
    success: function(msg){
            alert('Email Sent');
        }                   
    });
});



} 
于 2013-04-02T02:34:51.737 回答
0

您实际上并没有在 AJAX 请求中传递表单中的值,只是发出一个“空”的 POST 请求。您应该查看 AJAX 表单插件,它会为您完成繁重的工作:

http://www.malsup.com/jquery/form/

于 2013-04-02T02:36:01.333 回答