Javascript Fetch SYNTEXERROR:JSON.parse:JSON数据第1行第1列的意外字符
我正在处理一个联系人表单,这个错误正在阻止它工作。。。我可能在监督一些事情。有趣的是,如果我使用XMLHttpRequest而不是Fetch,我的代码就可以工作 使用Fetch时,如果我不请求响应,它不会抛出任何错误,但也不起作用。。正如您所看到的,我正在调试传递的参数,它们是正常的Javascript Fetch SYNTEXERROR:JSON.parse:JSON数据第1行第1列的意外字符,javascript,reactjs,fetch,phpmailer,Javascript,Reactjs,Fetch,Phpmailer,我正在处理一个联系人表单,这个错误正在阻止它工作。。。我可能在监督一些事情。有趣的是,如果我使用XMLHttpRequest而不是Fetch,我的代码就可以工作 使用Fetch时,如果我不请求响应,它不会抛出任何错误,但也不起作用。。正如您所看到的,我正在调试传递的参数,它们是正常的 handleSubmit(e) { /*var xhr = new XMLHttpRequest(); xhr.addEventListener('load', ()
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;
。。。
$sent=$mail->send();
回音“消息已发送”;
如果(isset($sent)&&$sent==true):?>
{
“状态”:“成功”,
“消息”:“您的数据已成功提交”
}
{
“状态”:“失败”,
“错误”:
}
也有看
async function handleSubmit(e) {
const response = await fetch("http://localhost:3002/index.php", {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(this.state) // body data type must match "Content-Type" header
});
if (response.status === 'success')
{
alert("Message Sent.");
this.resetForm()
}
else if(response.status === 'fail')
{
alert("Message failed to send.")
}
e.preventDefault();
}