PHP POST 使用 JS Fetch API

PHP POST using JS Fetch API

我不知道为什么它不起作用。它returns空$_POST.

JS:

const updateRequest = new FormData();
updateRequest.append('updateRequest', 'next-period');


fetch('file.php', {
  method: 'POST',
  data: updateRequest
})

  .then((response) => response.text())

  .then((text) => {
    console.log(text);
  })

PHP:

<?php

if($_SERVER['REQUEST_METHOD'] === 'POST') {

  var_dump(empty($_POST));

}

在 PHP 文件中,服务器请求是 POST 但 var_dump 记录为真。

根据 documentation,如果您想在请求正文中将数据发送到服务器(就像您对 POST 所做的那样),那么您可以将其放在 body选项。没有可用的 data 选项。如果您将它提供给 Fetch 方法,它不会期望它并且会简单地忽略它。也许您将它与 jQuery $.ajax() 的语法(确实有 data 选项)或其他语法混淆了?

你需要写:

fetch('file.php', {
  method: 'POST',
  body: updateRequest //"body" instead of "data"
})

演示(在 运行 fiddle 时观看网络选项卡以查看正文中包含的数据):http://jsfiddle.net/2vx0rp3q/

更改正文中的数据

var form = new FormData(document.getElementById('login-form'));
fetch("/login", {
  method: "POST",
  body: form
});

此处定义 https://developer.mozilla.org/it/docs/Web/API/Fetch_API/Using_Fetch