数据正在通过 $http 发送到 php 文件,但 JSON 解码为空白或未定义?

Data is being sent via $http to php file but JSON decodes blank or undefined?

我正在通过 AngularJS 使用 $http 将数据发送到 PHP 文档,该文档旨在将数据保存在 MySQL 数据库中。但是,数据被解码为空白或未定义。 JSON 进入 PHP 文件,正如我看到的请求 headers,但响应是空白的。

我已经尝试测试代码的不同变体以确保 JSON-encoded 数据进入 PHP 文档,确实如此,但是当尝试 json_decode() 它时不会从 JSON.

中提取任何内容

PHP 文件

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user = $request->Username;
echo $user;

AngularJS

$scope.submit = function() {
        $http({
            url: "http://www.walkermediadesign.com/planner3/src/ceremony.php",
            method: "POST",
            data: this.ceremony
        }).then(function successCallback(response) {
            console.log(response.data);
        }, function errorCallback(response) {
            $scope.error = response.statusText;
    })};

这是post数据:

$postdata = 
(2) [{…}, {…}]
0: {Username: "redphyre@gmail.com"}
1: {opening: "Friends and Family of BRIDE and GROOM, welcome and…d 
falling in love with each other all over again."}
length: 2
__proto__: Array(0)

没有错误消息或 500 条错误,只是返回空白数据。

我认为您期待 JSON 如下所示的数据:

{
    "Username": "redphyre@gmail.com",
    "opening": "Friends and Family..."
}

您拥有一个具有所有预期属性的对象。

然而,您实际得到的是:

[
    { "Username": "redphyre@gmail.com" },
    { "opening": "Friends and Family..." }
]

这会创建一个对象数组,每个对象只有一个 属性,使用起来几乎没有那么容易。要将数据转换为具有多个属性的单个对象,您可以遍历结果集:

$responseData = new stdClass();

foreach ($response as $propertyObject) {
    $properties = get_object_vars($propertyObject);

    // Just in case some objects have more than one property after all
    foreach($properties as $name => $value) {
        $responseData->$name = $value;
    }
}

这会将响应数组中对象的各个属性复制到单个对象中。