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

问题描述 投票:5回答:3

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

这是我尝试过的:

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

PHP:

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

它是否正确?

fetch urlfetch fetch-api
3个回答
10
投票

这取决于:

如果你想要$_GET['x'],你需要在querystring中发送数据:

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);
});

8
投票

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

您正在“POST”或“GETting”的数据在超级全局变量中不可用,因为此输入不是来自多部分数据表单或application / x-www-form-urlencoded

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

希望它有所帮助。

你可以在这里阅读更多相关内容:

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


-1
投票

使用$_POST检索post变量。

$x = $_POST['x'];

undefined变量添加后备也是一种好习惯。

$x = isset($_POST['x']) ? $_POST['x'] : 'default value';
© www.soinside.com 2019 - 2024. All rights reserved.