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

AJAX请求经PHP处理返回NULL的问题求助

问题排查与修复方案

核心问题分析

你的AJAX请求存在3个关键错误,导致PHP无法正确解析请求体,最终返回NULL:


错误1:发送数据格式错误

xhr.send(JSON.parse(storedProduct)); 中,JSON.parse(storedProduct) 得到的是JavaScript对象/数组,而XMLHttpRequest的send方法接收非字符串类型时,会自动将其转为"[object Object]"这类无效字符串,后端json_decode自然解析失败。

修复:将对象转为标准JSON字符串后发送:

xhr.send(JSON.stringify(products)); // 直接复用已解析好的products变量

错误2:请求URL缺少协议

xhr.open("POST", "localhost:9000/frontEndProductsHandler.php",true); 中的URL未指定协议(http://或https://),浏览器会将其当作当前页面的相对路径处理,导致请求发送到错误地址。

修复:补充协议前缀:

xhr.open("POST", "http://localhost:9000/frontEndProductsHandler.php", true);

错误3:错误设置响应头

xhr.setRequestHeader('Access-Control-Allow-Origin', '*'); 是后端响应时需要设置的头,前端请求时添加该头不仅无效,还可能触发浏览器预检请求异常。

修复:删除该行代码。


修正后的完整AJAX代码

const storedProduct = localStorage.getItem("product-id");
const products = JSON.parse(storedProduct);

(function products_to_backend() {
  let xhr = new XMLHttpRequest();
  xhr.open("POST", "http://localhost:9000/frontEndProductsHandler.php", true);
  xhr.setRequestHeader("Content-type", "application/json");
  
  xhr.addEventListener("load", function(){
    if(xhr.readyState === 4 && xhr.status === 201){ // 对应后端返回的201状态码
      console.log(`server status : 201 Created : ${xhr.responseText}`);
    } else if(xhr.status === 404){
      console.log("NOT FOUND");
    } else if(xhr.status === 400){
      console.log("Invalid JSON data");
    }
  });
  
  xhr.addEventListener("error", function(){
    console.log(`request failed : ${xhr.statusText}`);
  });
  
  console.log(typeof products); // 直接使用已解析的变量,避免重复解析
  xhr.send(JSON.stringify(products));
})();

额外验证点

  1. 确认localStorage.getItem("product-id")能获取到正确的JSON字符串,可在控制台打印storedProduct,检查格式是否与Postman提交的一致。
  2. 可在PHP中添加日志排查接收内容:
$requestBody = file_get_contents("php://input");
error_log("Received request body: " . $requestBody); // 查看服务器日志确认接收到的内容
$data = json_decode($requestBody);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:55:37