使用AJAX提交表单后PHP的$_POST为空,求助排查遗漏点
问题:AJAX提交表单后PHP的$_POST返回空值
问题描述
尝试用JavaScript的AJAX提交表单,JS代码如下:
const form = document.querySelector('#login'); form.addEventListener('submit', function (event) { event.preventDefault(); fetch('page.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(new FormData(this)) }) .then(response => response.json()) .then(result => { console.log('Success:', result); }) .catch(error => { console.error('Error:', error); }); });
对应的HTML表单代码:
<form id="login"> <div class="form-group mb-3"> <input type="email" class="form-control" name="USR_Email" placeholder="Email Address"> </div> <div class="form-group mb-3"> <input type="password" class="form-control" name="USR_Password" placeholder="Password"> </div> <div class="d-grid mt-4"> <button type="submit" class="btn btn-primary">Login</button> <input type="hidden" name="action" value="login"> </div> </form>
但PHP页面执行print_r($_POST);返回空值。
原因分析
- FormData无法直接被JSON.stringify序列化:FormData是特殊的不可枚举对象,直接用
JSON.stringify(new FormData(this))会得到空对象{},导致实际发送的请求体是空的。 - PHP的$_POST不自动解析JSON格式:你设置了请求头
Content-Type: application/json,但PHP的$_POST默认只处理application/x-www-form-urlencoded或multipart/form-data格式的请求,不会自动解析JSON数据。
解决方案
方法一:发送表单编码格式数据(推荐)
直接将FormData对象作为请求体提交,浏览器会自动设置正确的Content-Type,PHP的$_POST就能正常获取数据:
const form = document.querySelector('#login'); form.addEventListener('submit', function (event) { event.preventDefault(); fetch('page.php', { method: 'POST', body: new FormData(this) // 直接传递FormData对象 }) .then(response => response.json()) .then(result => { console.log('Success:', result); }) .catch(error => { console.error('Error:', error); }); });
此时PHP中print_r($_POST);即可输出表单数据。
方法二:使用JSON格式提交(需修改PHP逻辑)
如果需要坚持用JSON格式,先将FormData转为普通对象再序列化,同时PHP读取原始请求体解析:
修改后的JS代码:
const form = document.querySelector('#login'); form.addEventListener('submit', function (event) { event.preventDefault(); // 将FormData转换为可序列化的普通对象 const formDataObj = Object.fromEntries(new FormData(this)); fetch('page.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formDataObj) }) .then(response => response.json()) .then(result => { console.log('Success:', result); }) .catch(error => { console.error('Error:', error); }); });
修改后的PHP代码:
// 读取原始POST请求体 $rawPostData = file_get_contents('php://input'); // 解析JSON为关联数组 $formData = json_decode($rawPostData, true); // 输出解析后的数据 print_r($formData);
内容的提问来源于stack exchange,提问作者F__M
相关产品推荐
相关产品推荐

