使用Fetch发送POST请求无法获取PHP返回数据的问题
问题解决方法
前端代码错误修正
你的Fetch请求回调写法有误,导致无法执行后续逻辑,同时缺少必要的请求头,修正后的代码如下:
fetch("https://localhost/data.php", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ data1: data1, data2: data2 }) }) .then(res => res.json()) .then(json => { console.log("Successful fetch."); console.log(json); }) .catch(error => { console.log("Failed to fetch. " + error); });
问题原因
- 回调函数写法错误:原代码中
.then()和.catch()里用了json => function(json) {...}的写法,这会让箭头函数返回一个未执行的函数,Promise不会自动调用这个函数,所以你看不到任何日志输出,也无法处理返回的JSON数据。直接替换为代码块即可正常执行逻辑。 - 缺少请求头:发送JSON格式的请求体时,需要设置
Content-Type: application/json,告诉服务器请求数据的格式,避免后续处理POST数据时出现解析问题。
PHP代码优化(可选)
如果后续需要处理前端发送的JSON数据,可修改PHP代码如下,用于接收并返回处理结果:
<?php // 读取前端发送的JSON数据 $input = file_get_contents('php://input'); $receivedData = json_decode($input, true); // 返回包含接收数据的响应 echo json_encode([ "reply" => true, "received_data" => $receivedData ]); ?>
内容的提问来源于stack exchange,提问作者beans-are-gross
相关产品推荐
相关产品推荐

