首页 > 解决方案 > 如何在 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 吗?谢谢!

标签: javascriptphpjsoncross-domain

解决方案


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


推荐阅读