【问题标题】:How to read json request in a ZF2 Controller?如何在 ZF2 控制器中读取 json 请求?
【发布时间】:2016-02-21 21:55:26
【问题描述】:

我已经在前端和后端使用 Zend Framework 2 进行了开发。我想使用 Angular JS 从前端发送一个 json 到后端,并在 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!!!");
        });         
    }

另一方面,后端,在我的控制器中,我有下一个代码:

控制器

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

如果我从后端删除这行代码:

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

代码运行良好。即前端调用和接收结果“0”写在控制台“结果OK!!!”。但是如果我不删除那行代码,在前端我不会收到任何结果,因为后端的某些东西不能正常工作。

如何在控制器中读取从前端接收到的数据?

更新 1

我添加了更多信息以从前端发送到后端:

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

我在前端修改了我的 var 数据,并从调用后端中删除了配置:

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

遗憾的是,这行代码没有返回任何内容。

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

我在 console.log 中有这个错误:

并且,如果我在我的控制器中更改这行代码,则无需更改前端的任何内容:

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

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

【问题讨论】:

标签: php json angularjs zend-framework


【解决方案1】:

你不需要使用:

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'] ....

【讨论】:

  • 谢谢Szymon,但我不知道我做错了什么,因为它对我不起作用:(
  • 尝试删除 $.param 并且只删除 var data = { id: $scope.user.id, profiles: 2, user: "John", color: "blue" }。并检查另一个字段而不是“id”(可能是“用户”)
  • 所以.....像以前一样添加这个 $.param 但是尝试: headers: {'Content-Type': 'application/x-www-form-urlencoded'} (而不是 json header )。更改标题后 PHP 应该会看到这个。
  • 我已经检查过了,它有效!!!但是如果我发送一个json不起作用!!!我不明白:-(
  • 如果你想在控制器中通过 Angular 发送 json 标头,你必须使用:$params = json_decode(file_get_contents('php://input'),true);
猜你喜欢
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-23
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多