【问题标题】:How to get the json data from xhr fetch (after CORS) back in php如何在 php 中从 xhr fetch(在 CORS 之后)获取 json 数据
【发布时间】: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


【解决方案1】:

好的,我找到了一个可能让我更进一步的解决方案。我需要 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>

【讨论】:

  • 这只是撤消 the response.json() call 的操作,它将 JSON 字符串转换为对象。如果你只想要文字,你可以use response.text() instead。不管怎样,你仍然没有向任何 PHP 代码传递任何东西,所有这些逻辑都发生在浏览器中,在 PHP 代码运行很久之后。
猜你喜欢
  • 2015-07-15
  • 2018-03-30
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多