【发布时间】:2021-12-07 13:25:39
【问题描述】:
我正在使用 CORS 获取 JSON 数据,并且我在控制台中成功获取了 JSON 数据。现在我想用 PHP 显示获取的数据。下面的代码将获取的数据导入 PHP 之后的下一步是什么?
<script>
fetch("http://localhost:8000/get_users.php", {
method: 'post',
credentials: 'include'
}).then(response => {
return response.json();
}).then(users => {
console.log(users);
});
</script>
我试图在$_POST:
$posted_data = array();
if (!empty($_POST['users'])) {
$posted_data = json_decode($_POST['users'], true);
}
print_r($posted_data);
但是users 是未定义的。
有人知道如何将获取的 JSON users 放入 PHP 中吗?
谢谢!
【问题讨论】:
-
我有点困惑。您正在记录的数据是来自 PHP 代码的响应,并且似乎没有任何您要发布到 PHP 的数据。您期望“用户”来自哪里?
-
你没有传递任何数据?
-
数组 $users 在 localhost:8000 的 get_users.php 中,并与 CORS 一起作为 JSON 发送到 localhost:80,然后 JSON 从 localhost:80 控制台登录到控制台。所以数据通过了。但我无法将它从 JSON 恢复到 PHP……
-
如果你想在 PHP 中(在服务器上)获取数据,你不应该使用 JavaScript(在浏览器中)来获取它。另见What is the difference between client-side and server-side programming?
标签: javascript php json cross-domain