javascript - 如何在 php 中从 xhr fetch(在 CORS 之后)获取 json 数据
问题描述
我正在使用 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
是未定义的。
有人知道如何将获取的 JSONusers
转换为 PHP 吗?谢谢!
解决方案
好的,我找到了一个可能让我更进一步的解决方案。我需要JSON.stringify()
我获取的 JSON,这就是问题所在。
更新代码:
<script>
fetch("http://localhost:8000/get_users.php", {
method: 'post',
credentials: 'include'
}).then(response => {
return response.json();
}).then(users => {
console.log(users);
var users = JSON.stringify(users);
alert(users);
});
</script>
推荐阅读
- python - 查找用户输入的一组值的最大值而不将值存储在列表中
- r - Display Pie Chart Percentages in R studio from Dataset
- python - check if any character of a string is inside a list
- javascript - Alexa lambda JS how to access array data from external .js file
- python - 如何在 Python 中绘制对象路径的轨迹?
- apache-flink - Flink 算子之间共享状态
- python - 为什么使用 Keras API 将最大池替换为平均池会失败?
- mysql - 如何在 REST 服务器(NodeJS、MySQL)的 PUT 方法中传递正确的参数
- python - Multiple Locations for Python Packages
- php - 如何允许具有“作者”角色的用户发布用户定义类型的记录,并且只有作者才能阅读记录?