为什么 PHP 无法从 Js FormData 获取 $_POST 数据?

Why PHP couldn't get $_POST data from Js FormData fetch?

我想发送 JSON 数据(在本例中是客户端时间戳)到我的服务器。但是,我的代码似乎并没有像我预期的那样工作。

我的想法是使用 fetch 将 FormData(包含一个具有 JSON 作为值的输入)发送到 PHP。在服务器端,PHP 会处理带有 $_POST 和 return JSON 字符串的表单给我。

我正在使用免费的主机服务,它有 PHP 7.0,用于测试内容。

以下所有代码都在同一个文件中 (404.php):

var now = new Date();

var pkg = JSON.stringify({
    ts: now.getTime(),
    tz: now.getTimezoneOffset() / -60
})

var form = new FormData();
form.set('json', pkg);

console.log(form.has('json')) // true
console.log(form.values().next()) // return and obj contain JSON string

fetch('/404.php', {
    method: 'POST',
    body: form
});
$json = null;
if(isset($_POST['json'])) $json = json_decode($_POST['json']);

var_dump($_POST); //Result: array(0) { }

如您所见,var_dump 的输出是一个空数组。但我希望看到的是带有 JSON 字符串的输出。

我试过另一种方法,就是这个fetch-api-json-php,但也没用。我在 Internet 上找到的所有资源通常都是关于经典 AJAX,而不是 fetch API。而且其中大部分仅适用于客户端,PHP/server 端我找不到太多。

这对我有用:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script>
    var pkg = '{"test":"data"}';
    var formData = new FormData();
    formData.set('json', pkg);

    fetch('./404.php', {
      method: 'POST',
      body: formData
    });
</script>
</head>
<body>

</body>
</html>

PHP:

<?php
$json = null;
if(isset($_POST['json'])) 
    $json = json_decode($_POST['json']);

var_dump($_POST, $json); 

// Result: array(1) { ["json"]=> string(15) "{"test":"data"}" } object(stdClass)#1 (1) { ["test"]=> string(4) "data" } 

?>

您可以尝试 运行 在您的本地机器上执行此代码吗?

创建文件名 55788817.php 并粘贴此代码和 运行。

  <?php
  if (isset($_POST) && !empty($_POST)) {
    $json = null;
    if(isset($_POST['json'])) $json = json_decode($_POST['json']);

    var_dump($_POST); //Result: array(1) { ["json"]=> string(29) "{"ts":1555915560755,"tz":5.5}" }
    exit;
  }
  ?>
  <!DOCTYPE html>
  <html>
  <head>
    <title></title>
  </head>
  <body>
    <button type="button" id="registerButton">Click Me!</button>
    <script>
      var now = new Date();

      var pkg = JSON.stringify({
          ts: now.getTime(),
          tz: now.getTimezoneOffset() / -60
      })

      var form = new FormData();
      form.append('json', pkg);

      console.log(form.has('json')) // true
      console.log(form.values().next()) // return and obj contain JSON string
      fetch('./55788817.php', {
          method: 'POST',
          body: form
      });
    </script>
  </body>
  </html>