我通过ajax发送电子邮件来联系php。 PHP脚本成功发送了电子邮件,但是即使xmlhttp.status为200,Ajax xmlhttp.readyState仍然重试2。

params = "name=" + name + "&email=" + email + "&message=" + message + "&telephone=" + telephone;

xmlhttp.open("POST", "contact.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){

        if(xmlhttp.responseText == "fill_form"){
            note.innerHTML = "Please fill the required fields properly";
            return;
        }

        if(xmlhttp.responseText == "Sent"){
            serverMessage.innerHTML = "Thanks. If it is a request or complaint we well get back to you soon";
        }
    }
    else{
        serverMessage.innerHTML = "Some internal error occured while sending the email. Please try again later";
        $('#myModal').modal('show')
    }

    submitBtn.innerHTML = "SEND MESSAGE";
    submitBtn.disabled = false;
}


Contact.php

<?php

$name=$_POST['name'];
$email=$_POST['email'];
$message=$_POST['message'];
$telephone=$_POST['telephone'];

$mail_to_send_to = "[email protected]";
$feed_back_mail = "[email protected]";

if (empty($name) || empty($email)|| empty($message))
{
    echo "fill_form";
}
else{

    $from="From:$feed_back_mail"."\r\n"."Reply-To:$email"."\r\n" ;
    $subject="Users feed back Contact";

    if(empty($telephone)){
        $telephone = "No telephone sent my user";
    }

    $message = "Telephone: $telephone\r\nSender's Email : $email \r\n \r\n$message \r\n";

$isSent = mail($mail_to_send_to, $subject, $message, $from);

    if($isSent){
        echo $isSent;
    }
    else{
        echo "not_sent";
    }
}


?>

怎么了?

最佳答案

请记住,随着就绪状态的改变,您的onreadystatechange回调将被多次调用。您当前的代码将响应第一个回调,期望它能够完成。但是,在此之前使用readyState 2(“收到标题”)打个电话是很正常的。

因此,只要等到得到readyState 4:

xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4){
        // Done, what happened?
        if(xmlhttp.status == 200){
            // All good
        }
        else{
            // Something went wrong
        }
    }
};

关于javascript - 即使xmlhttp.status等于200,xmlhttp.readyState也会返回2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38157820/

10-13 00:50