【发布时间】:2020-01-24 11:42:53
【问题描述】:
我正在处理一个联系表单,这个错误正在阻止它工作......我可能正在监督一些事情。有趣的是,如果我使用 XMLHttpRequest 而不是 Fetch,我的代码就可以工作。
使用 Fetch 时,如果我不请求响应,它不会向我抛出任何错误,但也不起作用。如您所见,我正在调试正在传递的参数,它们没问题。
handleSubmit(e)
{
/*var xhr = new XMLHttpRequest();
xhr.addEventListener('load', () => {console.log(xhr.responseText)});
xhr.open('POST', 'http://localhost:3002/index.php');
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(this.state));*/
fetch('http://localhost:3002/index.php',
{
method: "POST",
body: JSON.stringify(this.state),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
}).then(
console.log(JSON.stringify(this.state))
).then(
(response) => (response.json())).then((response)=>
{
if (response.status === 'success')
{
alert("Message Sent.");
this.resetForm()
}
else if(response.status === 'fail')
{
alert("Message failed to send.")
}
})
e.preventDefault();
}
以及来自 php 方面的响应:
...
$sent = $mail->send();
echo 'Message has been sent';
if (isset($sent) && $sent === true) : ?>
{
"status": "success",
"message": "Your data was successfully submitted"
}
<?php endif;
}
catch (Exception $e)
{
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
}
else if (!empty($errors)) : ?>
{
"status": "fail",
"error": <?php echo json_encode($errors) ?>
}
<?php endif;
【问题讨论】:
标签: javascript reactjs fetch phpmailer