AngularJs-PHP POST问题

时间:2018-11-29 10:03:29

标签: php angularjs angularjs-http

我正在尝试使用angularjs向php发出发布请求。发布响应始终为200 OK,并且响应中返回的“ data”变量始终为空。如您所见,我对此很陌生,在这里我做错了什么?

AngularJs代码:

$scope.postData = function(){
    $http.post('send.php', $scope.data).then(function(response){
      console.log(response);
    });
  }

PHP:

$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();

if(empty($form_data->fullName)){
  $error["fullName"] = "Your name is required";
}

if(empty($form_data->email)){
  $error["email"] = "Your email is required";
}

if(empty($form_data->message)){
  $error["message"] = "Message is required";
}

if(!empty($error)){
  $data["error"] = $error;
} else {
  $data["message"] = "Ok";
}

1 个答案:

答案 0 :(得分:1)

您需要将数据回显给客户端,在您的代码中您不返回任何内容,因此响应为空。

<?php
$form_data = json_decode(file_get_contents("php://input"));
$data = array();
$error = array();

if(empty($form_data->fullName)){
  $error["fullName"] = "Your name is required";
}

if(empty($form_data->email)){
  $error["email"] = "Your email is required";
}

if(empty($form_data->message)){
  $error["message"] = "Message is required";
}

if(!empty($error)){
  $data["error"] = $error;
} else {
  $data["message"] = "Ok";
}

echo json_encode($data); // return data back to the client