You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 19:26:28