CORS跨域后fetch获取的JSON数据如何在PHP中接收并展示
问题解决方法
核心问题原因
你当前的逻辑存在两处错误:
- 第一次发起
fetch请求get_users.php时,你还没有拿到users数据,不可能在这个请求里把还未获取的数据传给后端,此时在get_users.php中读$_POST['users']必然不存在。 - 拿到
users数据后,你没有主动发起携带users数据的POST请求给PHP,后端自然无法接收。
解决方案
你需要在拿到users的回调中,再发起一次带数据的POST请求到专门接收数据的PHP脚本即可,代码修改如下:
前端代码修改
<script> fetch("http://localhost:8000/get_users.php", { method: 'post', credentials: 'include' }).then(response => response.json()) .then(users => { console.log(users); // 新增:把拿到的users传给接收用的PHP fetch("http://localhost:8000/receive_users.php", { method: 'POST', credentials: 'include', headers: { // 指定表单格式提交,PHP可直接读取$_POST 'Content-Type': 'application/x-www-form-urlencoded', }, // 把users转成JSON字符串编码后作为参数传递 body: 'users=' + encodeURIComponent(JSON.stringify(users)) }).then(res => res.text()) .then(phpResult => { // 可直接把PHP返回的结果渲染到页面 document.body.insertAdjacentHTML('beforeend', phpResult); }) }); </script>
后端PHP代码(receive_users.php)
你原有代码可直接复用:
<?php $posted_data = array(); if (!empty($_POST['users'])) { $posted_data = json_decode($_POST['users'], true); } print_r($posted_data); ?>
可选方案:发送JSON格式请求
如果你不想用表单格式提交,也可以直接传JSON结构,修改对应代码即可:
前端fetch配置修改
fetch("http://localhost:8000/receive_users.php", { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(users) })
对应PHP接收代码修改
<?php // 读取原生请求体解析JSON $jsonRaw = file_get_contents('php://input'); $posted_data = json_decode($jsonRaw, true) ?: []; print_r($posted_data); ?>
内容的提问来源于stack exchange,提问作者alexcc
相关产品推荐
相关产品推荐

