Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript PHP:使用fetch()发送数据_Javascript_Php_Fetch - Fatal编程技术网

Javascript PHP:使用fetch()发送数据

Javascript PHP:使用fetch()发送数据,javascript,php,fetch,Javascript,Php,Fetch,我试图使用fetch()发送一些数据,但作为回报,我得到了 SyntaxError:位置23处的JSON中的意外标记 这就是我要做的 fetch('/api.php', { method: 'POST', body: JSON.stringify({ nom : "Issa", prenom: "Oule"}), headers : {"Content

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

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

这就是我要做的

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文件中:

    <?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"}';
}

?>

有人能帮我吗


提前感谢

您正在创建的JSON字符串中有一个伪分号:

echo '{"status":"ok", "Nom": '. $decoded['nom'];.', "Prenom": '.$decoded['prenom'].'}';
                                               ^ here
但这不是你唯一的错误

最好创建一个数组并使用
json\u encode()
创建json:

$jsonData = ["status"=>"ok", "Nom"=>$decoded['nom'], "Prenom"=>$decoded['prenom']];
echo json_encode($jsonData);

只需将echo语句更改为返回json_encode数组,如下所示

echo json_encode([
            "status" => "ok",
            "Nom" => $decoded['nom'],
            "Prenom" => $decoded['prenom']
        ]);

不要手动构建json。相反,创建一个数组,然后使用以确保它的格式正确最有可能的是,在
“nom:”中,nom、prenom周围缺少双引号$已解码['nom'];',“Prenom”:“.$decoded['Prenom']”。
但如前所述,使用
json\u encode()
执行此操作,因为utf字符也需要处理。