【问题标题】:AngularJs - PHP POST issueAngularJs - PHP POST 问题
【发布时间】:2019-05-01 08:38:30
【问题描述】:

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

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";
}

【问题讨论】:

  • echo json_encode($data) 最后你没有将任何数据返回给客户端
  • 天啊!谢谢你。我现在觉得自己好傻。
  • 那是编程,会发生这些事情

标签: php angularjs angularjs-http


【解决方案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

【讨论】:

  • 谢谢!就是这样!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 2016-02-06
  • 2016-11-10
  • 2019-08-18
  • 2012-01-18
相关资源
最近更新 更多