[英]Fetch SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I am working on a contact form and this error is stoping it from working... i might be overseeing something.我正在处理联系表格,但这个错误正在阻止它工作......我可能正在监督某事。 The funny part is that my code works if i use XMLHttpRequest instead of Fetch..
有趣的是,如果我使用 XMLHttpRequest 而不是 Fetch,我的代码就可以工作。
When using Fetch if i don't request for a response it doesn't throw me any error but doesn't work either.. As you can see i am debugging the parameteres being passed, and they are ok.使用 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();
}
And the response from php side:来自 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;
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();
}
Also have look at using_fetch也看看using_fetch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.