Ajax POST请求后无法获取服务器返回JSON数据问题求助
问题分析与解决
核心问题1:前端代码语法错误
你的JavaScript代码中,fetch配置对象里的headers属性末尾缺少逗号,导致语法错误,浏览器无法正确识别POST请求配置,最终默认以GET方式发送请求,因此PHP中if($_SERVER['REQUEST_METHOD'] === 'POST')的判断永远不会触发,自然不会返回你期望的JSON数据。
核心问题2:未解析响应体
即使请求成功返回JSON,你直接打印的Response对象只是响应的元数据(比如状态码、响应头等),不是实际返回的内容,需要调用response.json()方法才能解析出JSON格式的响应体。
修正后的完整代码
<?php if($_SERVER['REQUEST_METHOD'] === 'POST'){ // ajax handler $arr = ['profile' => 'Information about Fred']; // 设置响应头为JSON格式,让前端正确识别 header('Content-Type: application/json'); echo json_encode($arr); exit(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <p> Fred <button data-person='Fred'>Post Data</button> </p> <script> const button = document.querySelector('button'); button.addEventListener('click', function(){ const body = JSON.stringify({person: button.dataset.person}); fetch( './', { headers: {'Content-Type': 'application/json'}, // 补上缺失的逗号 method: 'POST', body: body } ) .then(function(response){ // 解析JSON响应体 return response.json(); }) .then(function(data){ // 打印实际返回的数据 console.log(data); }) .catch(function(error){ // 捕获请求或解析错误 console.error('Error:', error); }); }); </script> </body> </html>
额外优化说明
- 在PHP中添加
header('Content-Type: application/json');,明确告诉浏览器返回的是JSON格式数据,避免解析歧义。 - 增加
catch块捕获请求过程中可能出现的错误,方便调试。
内容的提问来源于stack exchange,提问作者user3425506
相关产品推荐
相关产品推荐

