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

Fetch API POST请求服务端无法接收数据问题排查

Fetch POST数据PHP服务端无法接收的解决办法

问题情况

客户端通过Fetch发送POST请求传递数据,客户端日志能确认所有参数都存在,但服务端返回结果显示未接收到任何数据,无法通过$_POST获取参数。

客户端代码

const formMobile = document.getElementById('quoteMobile');
if (formMobile) {
    formMobile.addEventListener('submit', function(e){  
      e.preventDefault()

console.log("submit fired");
console.log(            
                document.getElementById('fromDate').value +
                document.getElementById('toDate').value +
                 document.querySelector('input[name="unit"]:checked').value + 
                 document.getElementById("total").value +
                document.getElementById("lan").value
);
    
     fetch('/api/apicreatebooking.php', {
          method: 'POST',
          body: JSON.stringify({        
                fromDate: document.getElementById('fromDate').value,
                toDate: document.getElementById('toDate').value,
                apptmnt: document.querySelector('input[name="unit"]:checked').value,
                total: document.getElementById("total").value,
                lan: document.getElementById("lan").value
          }),
          headers: {
            'Content-type': 'application/json; charset=UTF-8',
          }
      })
    .then(function(response){ 
        return response.json()})
    .then(function(data){
console.log(data)
        body=document.getElementById("bodyDiv")
        messages=document.getElementById("messagesDiv");
        if (data.success) {
            bookingCode = data.bookingCode;
            phpFile = 'mbooking_form_content2.php'
            $('#bodyDiv').load('/presentation/' + phpFile + '?bookingCode=' + bookingCode);
        } else {
            messages.innerHTML = data.message;
        } 
    }).catch(error => console.error('Error:', error)); 
    });
    
}   

服务端原代码

<?php
$a="a>";
if (isset($_POST['fromDate'])) {$a += $_POST['fromDate'];}
if (isset($_POST['toDate'])) {$a += $_POST['toDate'];}
if (isset($_POST['apptmnt'])) {$a += $_POST['apptmnt'];}
if (isset($_POST['total'])) {$a += $_POST['total'];}
if (isset($_POST['lan'])) {$a += $_POST['lan'];}
$result = array(
    "success" => true,
    "message" => $a,
    "bookingCode" => '1234567'
);

$output = json_encode($result);
echo $output;
?>

问题原因

  1. PHP的$_POST超全局变量仅处理application/x-www-form-urlencoded(表单默认格式)或multipart/form-data(文件上传格式)的请求体。你发送的是application/json格式,所以$_POST中不会有数据。
  2. 服务端代码中用+=拼接字符串是错误的,PHP里字符串拼接应该用.或.=,+=是数字加法操作,即使拿到数据也会导致结果异常。

解决方法

方法一:服务端读取JSON格式数据

修改服务端代码,从原始请求流中读取JSON数据并解析:

<?php
// 读取原始JSON请求体
$jsonInput = file_get_contents('php://input');
$requestData = json_decode($jsonInput, true); // 转为关联数组

$a = "a>";
if (isset($requestData['fromDate'])) {$a .= $requestData['fromDate'];}
if (isset($requestData['toDate'])) {$a .= $requestData['toDate'];}
if (isset($requestData['apptmnt'])) {$a .= $requestData['apptmnt'];}
if (isset($requestData['total'])) {$a .= $requestData['total'];}
if (isset($requestData['lan'])) {$a .= $requestData['lan'];}

$result = array(
    "success" => true,
    "message" => $a,
    "bookingCode" => '1234567'
);

echo json_encode($result);
?>

这种方法适合前后端分离的场景,保持JSON格式传递数据更规范。

方法二:客户端发送表单格式数据

修改客户端Fetch请求,发送application/x-www-form-urlencoded格式的数据,这样服务端可以直接用$_POST获取(同时记得修正服务端的字符串拼接错误):

fetch('/api/apicreatebooking.php', {
    method: 'POST',
    body: new URLSearchParams({
        fromDate: document.getElementById('fromDate').value,
        toDate: document.getElementById('toDate').value,
        apptmnt: document.querySelector('input[name="unit"]:checked').value,
        total: document.getElementById("total").value,
        lan: document.getElementById("lan").value
    })
    // URLSearchParams会自动设置正确的Content-Type,无需手动添加
})

或者使用FormData对象(适合包含文件的表单,这里也适用):

const formData = new FormData();
formData.append('fromDate', document.getElementById('fromDate').value);
formData.append('toDate', document.getElementById('toDate').value);
formData.append('apptmnt', document.querySelector('input[name="unit"]:checked').value);
formData.append('total', document.getElementById("total").value);
formData.append('lan', document.getElementById("lan").value);

fetch('/api/apicreatebooking.php', {
    method: 'POST',
    body: formData
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:36:18