原生JS使用AJAX发送POST请求到PHP出现undefined index报错如何解决
问题原因
- 错误使用
getResponseHeader方法:该方法用于读取服务端返回的响应头,你需要用setRequestHeader设置发送给服务端的请求头,否则PHP无法识别请求体的编码格式,不会自动解析到$_POST数组 - 请求头Content-Type值拼写错误:正确的表单编码格式标识为
application/x-www-form-urlencoded,你代码中拼写为application/w-xxx-form-urlencoded,属于无效格式
修正后的JS代码
document.getElementById("btn1").addEventListener('click', xh ); function xh(){ const xhr = new XMLHttpRequest(); xhr.open('POST', 'req.php'); // 修正:设置请求头,修正拼写错误 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.onprogress = function () { // document.getElementById("loading").classList.remove("dis"); } xhr.onload = function () { console.log(this.responseText); } xhr.send("msg=hello"); }
补充验证说明
修改后原有PHP逻辑无需调整即可正常获取$_POST['msg']参数,输出set。如果仍有问题可以临时在PHP顶部加入var_dump(file_get_contents('php://input'));查看是否能拿到原始请求体,排查是否是网络请求层面的参数丢失问题。
内容的提问来源于stack exchange,提问作者Eeshaan Gupta
相关产品推荐
相关产品推荐

