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

jQuery转Fetch API后PHP无法获取POST数据问题求助

问题

将一段jQuery代码转换为原生JavaScript代码时遇到服务器返回空数组的问题,具体情况如下:

原jQuery代码

data.push({name: "value", value: "test"});

$.ajax({
    type: "POST",
    url: "src/routes.php",
    data: data,
    dataType: 'json',
})   

服务器端代码(routes.php)

print_r($_POST);

jQuery请求的服务器响应

Array
(
    [value] => test
)

编写的原生Fetch API代码

data.push({name: "value", value: "test"});

const request = new Request('src/routes.php', {
     headers: new Headers({
        'Content-Type': 'application/json'
     }),
     method: 'POST',
     body: JSON.stringify(data),
});

fetch(request).then(res => res.json()).then(res => console.log(res));

Fetch请求的服务器响应

Array
(
)
原因分析
  1. jQuery的$.ajax方法在传入data为[{name: "...", value: "..."}]格式的数组时,会自动将其转换为**application/x-www-form-urlencoded**(表单编码)格式的请求体(比如value=test),PHP的$_POST会自动解析这种格式的数据。
  2. 你写的Fetch代码设置了Content-Type: application/json,并将数组转为JSON字符串作为请求体,但PHP的$_POST不会自动解析JSON格式的请求内容,所以$_POST为空数组。
解决方法

方法一:模拟jQuery的表单编码格式发送请求

将数据转换为URLSearchParams格式,保持和jQuery一致的请求体格式:

data.push({name: "value", value: "test"});

// 将数组转换为URLSearchParams
const formData = new URLSearchParams();
data.forEach(item => {
    formData.append(item.name, item.value);
});

const request = new Request('src/routes.php', {
     method: 'POST',
     body: formData,
});

fetch(request)
  .then(res => res.text()) // 服务器返回的是print_r的文本输出,不是JSON
  .then(res => console.log(res));

注意:无需手动设置Content-Type,浏览器会自动为URLSearchParams格式的请求体设置Content-Type: application/x-www-form-urlencoded。

方法二:修改PHP代码解析JSON请求体

如果想保持JSON格式的请求,可以修改PHP代码,直接读取原始请求体并解析:

// 读取原始请求内容
$rawData = file_get_contents('php://input');
// 解析为JSON数组
$data = json_decode($rawData, true);
// 输出结果
print_r($data);

对应的Fetch代码可保留原有写法,但需将响应解析方式改为res.text():

data.push({name: "value", value: "test"});

const request = new Request('src/routes.php', {
     headers: new Headers({
        'Content-Type': 'application/json'
     }),
     method: 'POST',
     body: JSON.stringify(data),
});

fetch(request).then(res => res.text()).then(res => console.log(res));

内容的提问来源于stack exchange,提问作者FireFoxII

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 02:45:36