【问题标题】:AngularJS Post data to PHP - trying to get property of non-objectAngularJS将数据发布到PHP - 试图获取非对象的属性
【发布时间】:2019-03-18 13:13:37
【问题描述】:

我一直在尝试将数据从 AngularJS 发布到 PHP 脚本,但遇到了一点问题。

$scope.submitRecipe = function () {
    $http({
        url: "../assets/php/scripts/create-recipe.php",
        method: "POST",
        data: {
            "recipeName" : $scope.recipeName
        }
    }).then(function (response) {
        alert(response.data);
    });
}

PHP 代码:

<?php
$request = json_decode(file_get_contents("php://input"));

echo $request->recipeName;
?>

当我提交(调用函数 submitRecipe())时,它确实返回了 recipeName,但它继续到我的 PHP 脚本,我得到了错误:

注意:试图在..中获取非对象的属性。

非常感谢任何帮助和指点。

【问题讨论】:

  • 是什么让你认为你在发送 JSON ......?
  • 您是否尝试过var_dump($_POST); 并检查过它为您提供了什么?你也可以试试var_dump(file_get_contents("php://input"));。如果您获得表单数据或 json,那应该会告诉您。
  • 您应该首先使用echo print_r($request, true) 打印$request 的内容。回显的响应将返回到 AngularJS,您将看到数据是否在往返过程中幸存下来。
  • @asiby 它提醒我我的期望,但随后它继续执行脚本并且没有显示任何内容。
  • 您希望它显示在哪里?除了警报(您说有效)之外,您没有做任何事情来显示响应。

标签: javascript php angularjs post


【解决方案1】:

我的猜测是json_decode 返回了null,导致这行抛出错误。

echo $request->recipeName;

检查数据是否返回

json_decode(file_get_contents("php://input"))

事实上不是nullContent-Typeapplication/json

【讨论】:

  • 运行var_dump(json_decode(file_get_contents("php://input"))); 返回string(0) ""。就像数据在继续执行脚本时被擦除一样。
猜你喜欢
  • 2017-01-26
  • 2017-08-21
  • 1970-01-01
  • 2011-08-02
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多