提交联系表格时,将返回PHP代码。之前运行良好。什么也没有变

时间:2018-12-14 07:56:38

标签: php html ajax

我有一个包含以下ajax和php代码的联系表:

<script>
function _(id){ return document.getElementById(id); }
function submitForm(){
    _("mybtn").disabled = true;
    _("status").innerHTML = 'please wait ...';
    var formdata = new FormData();
    formdata.append( "n", _("n").value );
    formdata.append( "e", _("e").value );
    formdata.append( "t", _("t").value );
    formdata.append( "m", _("m").value );
    var ajax = new XMLHttpRequest();
    ajax.open( "POST", "mail.php" );
    ajax.onreadystatechange = function() {
        if(ajax.readyState == 4 && ajax.status == 200) {
            if(ajax.responseText == "success"){
                _("my_form").innerHTML = '<h2>Thanks '+_("n").value+', your message has been sent.</h2>';
            } else {
                _("status").innerHTML = ajax.responseText;
                _("mybtn").disabled = false;
            }
        }
    }
    ajax.send( formdata );
}
</script>

mail.php的PHP代码:

<?php
if( isset($_POST['n']) && isset($_POST['e']) && isset($_POST['t']) && isset($_POST['m']) ){
    $n = $_POST['n']; // HINT: use preg_replace() to filter the data
    $e = $_POST['e'];
    $t = $_POST['t'];
    $m = nl2br($_POST['m']);
    $to = "myemail@mydomain.com";
    $from = $e;
    $subject = 'Contact Form Message';
    $message = '<b>Name:</b> '.$n.' <br><b>Email:</b> '.$e.' <br><b>Telephone:</b> '.$t.' <p>'.$m.'</p>';
    $headers = "From: $from\n";
    $headers .= "MIME-Version: 1.0\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1\n";
    if( mail($to, $subject, $message, $headers) ){
        echo "success";
    } else {
        echo "The server failed to send the message. Please try again later.";
    }
}
?>

它工作正常,但是我刚刚检查了一下,当我单击Submit按钮时,PHP代码已打印出来。它不会将包含所有信息的电子邮件发送到我的邮箱。这段代码有什么问题吗?还是我可以这样做更简单? 我没有PHP或Ajax的背景。

0 个答案:

没有答案