gpt4 book ai didi

javascript - 即使 xmlhttp.status 等于 200,xmlhttp.readyState 返回 2

转载 作者:行者123 更新时间:2023-11-28 05:49:59 27 4
gpt4 key购买 nike

我正在通过ajax发送电子邮件来联系php。 Php 脚本成功发送电子邮件,但 ajax xmlhttp.readyState 始终返回 2,即使 xmlhttp.status 为 200。

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;
}

联系方式.php

<?php

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

$mail_to_send_to = "abc@gmail.com";
$feed_back_mail = "name@myDomainName.com";

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(“收到 header ”)之前接到一个调用,这是很正常的。

所以只要等到你得到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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com