当 send 在 Javascript 中抛出 fetch() 时,无法在 php 中显示 JSON 代码

Can't display JSON code in php when send threw fetch() in Javascript

我试图用 php 将我的 json 回显到我的 html 页面,但它只在控制台打印或返回错误。 我对此很陌生,所以请帮忙。

这是 javascript,带有提取和激活的 onclick 提交一个到 php

async function hey(){
let click = 1;

await fetch('data.php',{
    method: 'POST',
    header: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(click),
}).then(response => response.json())
.then(data => {
  console.log(data);
})
.catch((error) => {
  console.error(error);
});}

这是 php 但它只会打印到控制台

<?php
$json = file_get_contents('php://input');

echo $json;
?>

让我们描述一下你在做什么:

首先,您调用方法的方式:

async function hey(){
  let click = 1;

  await fetch('data.php',{
    ...
}

如果你想通过你的函数 return json 的值,那么你必须 return 它。我认为你应该从方法中得到它,所以你可以更改为:

async function hey(){
  let click = 1;

  return await fetch('data.php',{
    ...
}

像这样你的函数实际上是 returning 东西。如果您从 return 通过 then() 的调用期望它,它不会工作,它是一个更深的范围。

我觉得 fetch 部分没问题,所以我直接跳到 then() 部分,实际上看起来像:

.then(response => response.json())
.then(data => {
  console.log(data);
 ....

我相信您不需要在此处调用 2 次 then() 方法。你可以简单地做:

 then(response => return response.json())

我没试过,但我认为你不需要调用 json 方法,因为你已经在发送 json。但要做到这一点,您需要在 php 中包含精确它所需的 headers,因为 php 不知道您正在发送 json 并且可能会做其他事情。所以你的 php 脚本应该是这样的:

<?php
header('Content-Type: application/json; charset=utf-8');
$json = file_get_contents('php://input');

echo $json;

干杯