$http ajax AngularJS POST返回PHP中未定义的索引

时间:2022-10-17 11:05:47

I'm sending data to an API REST service via the ajax $http service of AngularJS but php always says that the index is undefined. I've checked a lot of posts on SO that ask for the same error and I tried everything that they say but I still get the same error.

我通过AngularJS的ajax $http服务向API REST服务发送数据,但是php总是说索引没有定义。我检查了很多帖子,所以要求相同的错误,我尝试了所有他们说的,但我仍然有相同的错误。

How I'm using the $http service:

如何使用$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);
});

How I try to get values in PHP:

如何在PHP中获取值:

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

In this case, for example, it always says that title is an undefined index of $_POST

例如,在本例中,它总是说title是$_POST的未定义索引

2 个解决方案

#1


2  

To read data first you need to decode it in POST format.

要先读取数据,你需要用POST格式进行解码。

$json_input = file_get_contents('php://input');

if ($json_input) {
    $_REQUEST = json_decode($json_input, true);
}

#2


0  

Since you are posing data it application/json format you need to read it from raw POST data. Try this:

由于您正在提交数据it应用程序/json格式,所以需要从原始POST数据中读取它。试试这个:

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

#1


2  

To read data first you need to decode it in POST format.

要先读取数据,你需要用POST格式进行解码。

$json_input = file_get_contents('php://input');

if ($json_input) {
    $_REQUEST = json_decode($json_input, true);
}

#2


0  

Since you are posing data it application/json format you need to read it from raw POST data. Try this:

由于您正在提交数据it应用程序/json格式,所以需要从原始POST数据中读取它。试试这个:

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