欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > php >内容正文

php

fetch() php,PHP:使用fetch()发送数据

发布时间:2024/9/27 php 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 fetch() php,PHP:使用fetch()发送数据 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

我试图使用fetch()发送一些数据,但作为回报,我得到

SyntaxError:意外的标记,在JSON中的位置23

这就是我要做的

fetch('/api.php', {

method: 'POST',

body: JSON.stringify({

nom : "Issa",

prenom: "Oule"}),

headers : {"Content-Type" : "application/json"},

})

.then(res => res.json())

.then((res) => {

console.log(res);

})

.catch((err) =>{

console.log(err);

})

在我的php文件中:

header('Access-Control-Allow-Origin: *');

header('Content-Type: application/json');

header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');

header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';

if($contentType === "application/json") {

$content = trim(file_get_contents("php://input"));

$decoded = json_decode($content, true);

if(! is_array($decoded)) {

echo '{"status":"error decoding"}';

} else {

echo '{"status":"ok", "Nom": '. $decoded['nom'];.', "Prenom": '.$decoded['prenom'].'}';

}

}else{

echo '{"status":"error data"}';

}

?>

有人能帮我吗

提前谢谢

总结

以上是生活随笔为你收集整理的fetch() php,PHP:使用fetch()发送数据的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。