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

WordPress中AngularJS $http传数组至PHP接收为null的问题排查

解决AngularJS $http向WordPress PHP传递数组返回null的问题

嘿,我来帮你排查这个问题!你遇到的null问题其实是AngularJS $http的参数配置搞错了,跟WordPress本身支持不支持传递数组没关系~

核心问题:你用错了$http的参数位置

你在$http配置里用了params属性,这个属性是用来设置**URL查询参数(GET参数)**的,不是POST请求体里的参数。所以你在PHP里用$_POST去接收,自然拿不到任何数据,返回null。

两种正确的解决方式

方式一:用data属性发送POST请求体(推荐)

把要传递的数组放在data里,Angular会帮你处理序列化,PHP需要从请求体读取JSON数据:

AngularJS代码:

$http({
  method: 'post',
  url: url,
  data: {
    'disable_comments_on_post_types': allTabData.disable_comments_on_post_types
  },
  headers: { 'Content-Type': 'application/json' } // 明确告诉服务器发送的是JSON
});

PHP接收代码:
因为发送的是JSON格式的请求体,PHP不能直接用$_POST获取,需要从php://input读取后解析:

// 读取请求体的JSON数据
$rawJson = file_get_contents('php://input');
// 解析成关联数组(第二个参数true转数组,默认是对象)
$requestData = json_decode($rawJson, true);

// 现在就能正常获取数组里的值了
$postStatus = $requestData['disable_comments_on_post_types']['post'];
echo json_encode($postStatus);

方式二:如果坚持用params(参数会拼在URL里)

如果你还是想保留params的写法,那PHP里要从$_GET或者$_REQUEST里获取,再解析JSON字符串:

AngularJS代码:

var newdisable_comments_on_post_types = JSON.stringify(allTabData.disable_comments_on_post_types);
$http({
  method: 'post',
  url: url,
  params: {
    'disable_comments_on_post_types': newdisable_comments_on_post_types
  }
});

PHP接收代码:

// 从URL参数里获取JSON字符串
$jsonStr = $_REQUEST['disable_comments_on_post_types']; // 或者用$_GET['disable_comments_on_post_types']
// 解析成关联数组
$decodedData = json_decode($jsonStr, true);

// 获取对应的值
$postStatus = $decodedData['post'];
echo json_encode($postStatus);

为什么你之前的三种方式都失败?

  • 方式1:$_POST['disable_comments_on_post_types']['post'] —— $_POST里根本没有disable_comments_on_post_types这个键,因为参数在URL里,不是POST请求体,所以返回null。
  • 方式2:$_POST['disable_comments_on_post_types']同样是null,后续的foreach自然无法执行,结果还是null。
  • 方式3:试图用对象访问->post,但$a本身是null,所以访问属性也会返回null。

WordPress完全支持接收数组,只要传递方式正确,比如传统表单的name="disable_comments_on_post_types[post]"格式,或者上面的JSON方式都可以~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:26:10