如何在 ZF2 控制器中读取 json 请求?

How to read json request in a ZF2 Controller?

我在 front-end 和 back-end 中使用 Zend Framework 2 使用 Angular JS 进行了开发。我想从 [=107= 发送一个 json ] 到 back-end 使用 Angular JS 并在 Zend Framework 2 中阅读此 json。

Angular JS

    self.updateUser = function(user){
        var  data = JSON.stringify(
            {
                id: $scope.user.id
            }
        );

        var config = {
            headers: {
                 'Content-Type': 'application/json'
            }
        }

        $http.post("/privado/usuario/updateuser", data, config)
         .success(function(data, status, headers, config){
            switch (data.result){
                case 0: //OK
                    console.log("Result OK!!!");
                    break;
                case 1: //No tiene acceso
                    console.log("Resultado NO ACCESS!!!");
                    break;
                case 3: //Error de sistemas
                    console.log("Resultado KO!!!");
                    break;                  
             }
        })
        .error(function(data){
            console.log("Problems with the server!!!");
        });         
    }

在另一边,back-end,在我的控制器中我有下一个代码:

控制器

   public function updateUserAction(){
        $log = $this->getServiceLocator()->get("Zend/Log");

        $request = $this->getRequest();

        if ($request->isPost()){    

            $post_data = $request->getPost();       
            if ($post_data != null){
                try{
                    $json = Zend\Json\Json::decode($post_data, Zend\Json\Json::TYPE_ARRAY);
                    return new JsonModel(array(
                            "result"    =>  UsuarioController::RESULT_OK
                    ));
                }catch(\Exception $e){
                    //Error de acceso a BBDD
                    $log->info(get_class($this) . "::" . __FUNCTION__ . ": Se ha producido un error de acceso a BBDD o el elemento recibido no existe en BBDD. id: " + $post_data["id"]);
                    $log->info(get_class($this) . "::" . __FUNCTION__ . ": " . $e->getMessage());
                    return new JsonModel(array(
                            "result"    =>  UsuarioController::RESULT_SYSTEM_ERROR
                    ));
                }
            }else{
                $log->info(get_class($this) . "::" . __FUNCTION__ . ": No se ha recibido información a través de post");
                //Error al recibir los datos
                return new JsonModel(array(
                        "result"    =>  UsuarioController::RESULT_SYSTEM_ERROR
                ));
            }
        }
    }   

如果我从 back-end 中删除这行代码:

$json = Zend\Json\Json::decode($post_data, Zend\Json\Json::TYPE_ARRAY);

代码运行良好。也就是说,front-end 进行调用并接收类似在控制台 "Result OK!!!" 中写入的结果“0”。但是,如果我不删除那行代码,在 front-end 中我不会收到任何结果,因为 back-end 中的某些内容无法正常工作。

如何在我的控制器中读取从 front-end 接收到的数据?

已更新 1

我添加了更多信息以从 front-end 发送到 back-end:

Angular JS

    self.updateUser = function(user){
    var data = $.param({
        json: JSON.stringify({
            id: $scope.user.id,
            profiles: 2,
            user: "John",
            color: "blue"               
        })          
    });

    var config = {
        headers: {
             'Content-Type': 'application/json'
        }
    }

    $http.post("/privado/usuario/updateuser", data, config)
     .success(function(data, status, headers, config){
        switch (data.result){
            case 0: //OK
                console.log("Result OK!!!");
                break;
            case 1: //No tiene acceso
                console.log("Resultado NO ACCESS!!!");
                break;
            case 3: //Error de sistemas
                console.log("Resultado KO!!!");
                break;                  
         }
    })
    .error(function(data){
        console.log("Problems with the server!!!");
    });         
}

我也修改了Controller ...

控制器

   public function updateUserAction(){
    $log = $this->getServiceLocator()->get("Zend/Log");

    $request = $this->getRequest();

    if ($request->isPost()){   

        $post_data = $request->getPost();     
        if ($post_data != null){
            try{
                    $json = json_decode($post_data["data"]);
                    $log->info("Datos recibidos2: " . sizeof($json));
                    $log->info("id: " . $json["id"]);
                return new JsonModel(array(
                        "result"    =>  UsuarioController::RESULT_OK
                ));
            }catch(\Exception $e){
                //Error de acceso a BBDD
                $log->info(get_class($this) . "::" . __FUNCTION__ . ": Se ha producido un error de acceso a BBDD o el elemento recibido no existe en BBDD. id: " + $post_data["id"]);
                $log->info(get_class($this) . "::" . __FUNCTION__ . ": " . $e->getMessage());
                return new JsonModel(array(
                        "result"    =>  UsuarioController::RESULT_SYSTEM_ERROR
                ));
            }
        }else{
            $log->info(get_class($this) . "::" . __FUNCTION__ . ": No se ha recibido información a través de post");
            //Error al recibir los datos
            return new JsonModel(array(
                    "result"    =>  UsuarioController::RESULT_SYSTEM_ERROR
            ));
        }
    }
}   

这些代码行:

$log->info("Datos recibidos2: " . sizeof($json));
$log->info("id: " . $json["id"]);

将下一个结果写在文件中:

2015-11-19T18:23:30+01:00 INFO (6): Datos recibidos2: 0
2015-11-19T18:30:49+01:00 INFO (6): id:

我好像没有收到任何东西...我怎样才能收到收到的数据?

已更新 2

我已经在 front-end 中修改了我的 var 数据并删除了调用 back-end 的配置:

Angular JS

    self.updateUser = function(user){
    var data = $.param({
            id: $scope.user.id,
            profiles: 2,
            user: "John",
            color: "blue"               
    });

    $http.post("/privado/usuario/updateuser", data)
     .success(function(data, status, headers, config){
        switch (data.result){
            case 0: //OK
                console.log("Result OK!!!");
                break;
            case 1: //No tiene acceso
                console.log("Resultado NO ACCESS!!!");
                break;
            case 3: //Error de sistemas
                console.log("Resultado KO!!!");
                break;                  
         }
    })
    .error(function(data){
        console.log("Problems with the server!!!");
    });         
}

我也修改了Controller ...

控制器

   public function updateUserAction(){
    $log = $this->getServiceLocator()->get("Zend/Log");

    $request = $this->getRequest();

    if ($request->isPost()){   

        $post_data = $request->getPost();     
        if ($post_data != null){
            try{
                $log->info("id: " . $_POST["id"]);
                return new JsonModel(array(
                        "result"    =>  UsuarioController::RESULT_OK
                ));
            }catch(\Exception $e){
                //Error de acceso a BBDD
                $log->info(get_class($this) . "::" . __FUNCTION__ . ": Se ha producido un error de acceso a BBDD o el elemento recibido no existe en BBDD. id: " + $post_data["id"]);
                $log->info(get_class($this) . "::" . __FUNCTION__ . ": " . $e->getMessage());
                return new JsonModel(array(
                        "result"    =>  UsuarioController::RESULT_SYSTEM_ERROR
                ));
            }
        }else{
            $log->info(get_class($this) . "::" . __FUNCTION__ . ": No se ha recibido información a través de post");
            //Error al recibir los datos
            return new JsonModel(array(
                    "result"    =>  UsuarioController::RESULT_SYSTEM_ERROR
            ));
        }
    }
}   

遗憾的是,这行代码没有 return 任何东西。

$log->info("id: " . $_POST["id"]);
2015-11-19T19:24:29+01:00 INFO (6): id:

我在 console.log:

中遇到了这个错误

而且,如果我在我的控制器中更改这行代码,那么在 front-end 中不做任何更改:

$log->info("id: " . $_POST["id"]);

其他人:

$json = Zend\Json\Json::decode($post_data, Zend\Json\Json::TYPE_ARRAY);

并添加另一行以写入 "id" 的值:

$log->info("id: " . $json["id"]);

它不起作用,因为我在行中遇到错误:

$json = Zend\Json\Json::decode($post_data, Zend\Json\Json::TYPE_ARRAY);

因为在我的文件中我没有写任何东西。

已更新 3 从我上一个版本的代码中,如果我删除 $.param var 数据将是:

    var data = {
        id: $scope.user.id,
        profiles: 2,
        user: "John",
        color: "blue"               
    };

它不起作用,我在控制台中遇到了与以前相同的错误。我没有对控制器进行任何更改。

您不需要使用:

headers: {
             'Content-Type': 'application/json'
        }

和JSON解码:

$json = Zend\Json\Json::decode($post_data, Zend\Json\Json::TYPE_ARRAY);

您可以像以前一样使用 JSON 发送数据(或将 JSON.stringify 函数更改为字符串格式:{data1:value1, data2:value2 ...})并使用正常的 $_POST 获取它(没有 json_decode).

所以在JavaScript中你可以这样写:

var data = {
            id: $scope.user.id,
            profiles: 2,
            user: "John",
            color: "blue"                             
    };

并在 PHP 收到:

$_POST['id'], $_POST['profiles'], $_POST['user'] ....