如何在PHP中使用fetch() API POST方法获取数据?

2022-08-30 16:50:06

我正在尝试使用API POST方法来获取PHP中的POST数据。fetch()

以下是我尝试过的:

var x = "hello";
fetch(url,{method:'post',body:x}).then(function(response){
    return response.json();
});

菲律宾比索:

<?php
if(isset($_GET['x']))
{
    $get = $_GET['x'];
    echo $get;
}
?>

这是正确的吗?


答案 1

这取决于:

如果需要,则需要在查询字符串中发送数据:$_GET['x']

var url = '/your/url?x=hello';

fetch(url)
.then(function (response) {
  return response.text();
})
.then(function (body) {
  console.log(body);
});

如果需要,则需要将数据发送为:$_POST['x']FormData

var url = '/your/url';
var formData = new FormData();
formData.append('x', 'hello');

fetch(url, { method: 'POST', body: formData })
.then(function (response) {
  return response.text();
})
.then(function (body) {
  console.log(body);
});

答案 2

显然,当使用Fetch API将数据发送到PHP服务器时,您必须处理的请求与您习惯的请求略有不同。

您正在“POSTing”或“GETting”的数据在超级全局变量中不可用,因为此输入不是来自multipart-data formapplication/x-www-form-urlencoded

您可以通过读取特殊文件来获取数据:,例如使用,然后尝试使用 解码该输入。php://inputfile_get_contents('php://input')json_decode()

您可以在此处阅读更多相关信息:

https://codepen.io/dericksozo/post/fetch-api-json-php