如何在PHP中使用fetch()API POST方法获取数据? [英] How to grab data using fetch() API POST method in PHP?
问题描述
我试图使用 fetch()
API POST方法来获取PHP中的POST数据.
I am trying to use fetch()
API POST method in order to grab the POST data in PHP.
这是我尝试过的:
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 API将数据发送到PHP服务器时,您将不得不处理与以往稍有不同的请求
Apparently, when using the Fetch API to send data to a PHP server, you'll have to handle the request a little different from what you're used to.
您要发布"的数据或获取"在超级全局变量中将不可用,因为此输入不是来自多部分数据表单
或 application/x-www-form-urlencoded
The data you're "POSTing" or "GETting" is not going to be available in the super global variables since this input is not coming from a
multipart-data form
or an application/x-www-form-urlencoded
您可以通过读取特殊的文件: php://input
来获取数据,例如使用 file_get_contents('php://input')
,然后尝试使用 json_decode()
对该输入进行解码.
You can get your data by reading the special file: php://input
, for example using file_get_contents('php://input')
and then try to decode that input with json_decode()
.
您可以在此处了解更多信息:
You can read more about it here:
https://codepen.io/dericksozo/post/fetch-api-json-php
这篇关于如何在PHP中使用fetch()API POST方法获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!