【问题标题】:Request and response with Angular $post and PHP Codeigniter使用 Angular $post 和 PHP Codeigniter 请求和响应
【发布时间】:2016-11-29 12:06:39
【问题描述】:

当我通过 Angular $post 向 Codeigniter 发送数据时遇到问题。我正在使用这个 JS 代码:

 $scope.user.first_name = 'first name';
 $scope.user.last_name = 'last name';

 $http({
      method: 'POST',
      url: '/registration',
      data: {user: $.param($scope.user)},
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      }
 }).then(function successCallback(response) {
                 console.log(response)
         }, function errorCallback(response) {
                 console.log(response);
 });

我的 PHP 基于 StackOverflow 的另一个答案,但仍然无法正常工作:

echo file_get_contents('php://input');
var_dump($this->input->post());

,但是这样我看到响应空数组,如果我说:

var_dump($this->input->post('user'));

我看到响应 NULL,Same is and with:

var_dump(json_encode($this->input->post()));

有或没有“用户”键。即使我使用:

var_dump($_POST);

对于响应,我得到空数组。

如何使用 Codeigniter 通过 $post Angular 服务发送和获取数据?

【问题讨论】:

    标签: javascript php angularjs codeigniter


    【解决方案1】:

    如果你想发送表单编码数据,你需要用$.param()序列化整个数据对象

    变化:

     data: {user: $.param($scope.user)},
    

     data: $.param(angular.copy({user: $scope.user})),
    

    或使用$httpParamSerializerJQLike

    如果你使用 $http 的默认值,那就是

     $http.post( '/registration',$scope.user).then(...
    

    在php中

    $data = json_decode(file_get_contents('php://input'));
    

    【讨论】:

    • 响应仍然是一个数据为 NULL 的对象。
    • 使用您的代码,但不是默认值。使用这个 PHP $data = json_decode(file_get_contents('php://input'));var_dump(json_encode($data)); - 它返回字符串 NULL,没有 json_encode 只是 NULL。我在开发工具中看到请求是通过浏览器发送的。
    • 因为您需要在两端使用相同的内容类型。如果您发送编码的表单需要使用$_POST$this->input->post(),如果您默认发送为json,请使用file_get_contents
    • 非常感谢 :),现在使用 var_dump($this->input->post('user')); 可以正常工作。
    猜你喜欢
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    相关资源
    最近更新 更多