【问题标题】:$http ajax AngularJS POST returns undefined index in PHP$http ajax AngularJS POST 在 PHP 中返回未定义的索引
【发布时间】:2016-10-03 08:46:24
【问题描述】:

我通过 AngularJS 的 ajax $http 服务向 API REST 服务发送数据,但 php 总是说索引未定义。我检查了很多关于 SO 的帖子都要求同样的错误,我尝试了他们所说的一切,但我仍然得到同样的错误。

我如何使用$http 服务:

$http({
    method: 'POST',
    url: window.location.pathname+'/../../api/tasks/'+$id,
    data: {
        'title': $scope.allData.taskData[0].title,
        'content': $scope.allData.taskData[0].content,
        'usersInTask': $scope.allData.taskUsers
    },
    contentType: 'application/json',
    dataType: 'json',
    headers: {'Content-Type': 'application/json'}
})
.then(function success(response){

    $scope.closeDialog();
}, function error(response){
    console.log("Error:" +response.statusText);
});

我如何尝试在 PHP 中获取值:

$title = $_POST['title'];
$content = $_POST['content'];
$users = $_POST['users'];

例如,在这种情况下,它总是说title$_POST 的未定义索引

【问题讨论】:

    标签: javascript php jquery angularjs ajax


    【解决方案1】:

    由于您使用的是 application/json 格式的数据,您需要从原始 POST 数据中读取它。试试这个:

    $postData = json_decode(file_get_contents("php://input"));
    $title = $postData->title;
    $content = $postData->content;
    

    【讨论】:

    • 我能够得到这样的数据,但试图访问它的元素它只是说"Notice: Trying to get property of non-object"
    【解决方案2】:

    要首先读取数据,您需要以 POST 格式对其进行解码。

    $json_input = file_get_contents('php://input');
    
    if ($json_input) {
        $_REQUEST = json_decode($json_input, true);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 2014-12-19
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      相关资源
      最近更新 更多