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 ( )
原因分析
- jQuery的
$.ajax方法在传入data为[{name: "...", value: "..."}]格式的数组时,会自动将其转换为**application/x-www-form-urlencoded**(表单编码)格式的请求体(比如value=test),PHP的$_POST会自动解析这种格式的数据。 - 你写的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
相关产品推荐
相关产品推荐

