[英]How to read json request in a ZF2 Controller?
I have made a development with Angular JS in front-end and in back-end with Zend Framework 2. I want to send a json from front-end to back-end using Angular JS and read this json in Zend Framework 2. 我已经使用Angular JS在前端和后端使用Zend Framework 2进行了开发。我想使用Angular JS从前端向后端发送json,并在Zend Framework 2中阅读此json。
Angular JS 角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!!!");
});
}
On the other side, back-end, in my controller I have the next code: 另一方面,在后端,在我的控制器中,我有以下代码:
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 = 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
));
}
}
}
If I remove from back-end this line of code: 如果我从后端删除此代码行:
$json = Zend\Json\Json::decode($post_data, Zend\Json\Json::TYPE_ARRAY);
The code works fine. 该代码工作正常。 That is, the front-end makes the call and receive like result "0" writing in the console "Result OK!!!". 即,前端进行呼叫,并在控制台“ Result OK !!!”中写入类似结果“ 0”的消息。 But If I don't remove that line of code, in front-end I don't receive any result because something in back-end don't work fine. 但是,如果我不删除该行代码,则在前端我不会收到任何结果,因为后端的某些功能无法正常工作。
How can I read the data received from front-end in my controller? 如何在控制器中读取从前端接收的数据?
UPDATED 1 更新1
I have added more info to send from front-end to back-end: 我添加了更多信息,从前端发送到后端:
Angular JS 角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!!!");
});
}
And I have modified the Controller too ... 而且我也修改了控制器...
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
));
}
}
}
These lines of code: 这些代码行:
$log->info("Datos recibidos2: " . sizeof($json));
$log->info("id: " . $json["id"]);
Write me in a file the next result: 将我写到文件中的下一个结果:
2015-11-19T18:23:30+01:00 INFO (6): Datos recibidos2: 0
2015-11-19T18:30:49+01:00 INFO (6): id:
It seems like I don't receive anything ... How can I get the data received? 看来我什么都没收到。。。如何获取收到的数据?
UPDATED 2 更新2
I have modified my var data in front-end and remove config from calling to the back-end: 我已经在前端修改了var数据,并从调用后端删除了config:
Angular JS 角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!!!");
});
}
And I have modified the Controller too ... 而且我也修改了控制器...
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
));
}
}
}
Sadly, this line of code doesn't return anything. 可悲的是,这一行代码不返回任何内容。
$log->info("id: " . $_POST["id"]);
2015-11-19T19:24:29+01:00 INFO (6): id:
And I've got this error in the console.log: 而且我在console.log中遇到了这个错误:
And, without changing anything in front-end, if I change this line of code in my controller: 而且,如果不更改前端中的任何内容,则可以在控制器中更改以下代码行:
$log->info("id: " . $_POST["id"]);
By this other: 通过这个:
$json = Zend\Json\Json::decode($post_data, Zend\Json\Json::TYPE_ARRAY);
And add this other line to write the value of "id": 并添加另一行以写入“ id”的值:
$log->info("id: " . $json["id"]);
It doesnt' work, because I've got an error in the line: 它不起作用,因为我在该行中有一个错误:
$json = Zend\Json\Json::decode($post_data, Zend\Json\Json::TYPE_ARRAY);
Because in my file I don't write anything. 因为在我的文件中我什么都没写。
UPDATED 3 From my last version of code, if I remove $.param var data would be: 更新3从我的上一个代码版本中,如果删除$ .param,则var数据将为:
var data = {
id: $scope.user.id,
profiles: 2,
user: "John",
color: "blue"
};
It doesn't work and I've got the same error in the console than before. 它不起作用,并且控制台中的错误与以前相同。 I haven't made any change in the controller. 我尚未对控制器进行任何更改。
You don't need to use: 您不需要使用:
headers: {
'Content-Type': 'application/json'
}
and JSON decoding: 和JSON解码:
$json = Zend\Json\Json::decode($post_data, Zend\Json\Json::TYPE_ARRAY);
You can just send data using JSON as you did (or change JSON.stringify
function to string in format: {data1:value1, data2:value2 ...}
) and get it using normal $_POST
(without json_decode
). 您可以像以前一样使用JSON发送数据(或将JSON.stringify
函数更改为格式为{data1:value1, data2:value2 ...}
字符串),并使用普通的$_POST
(不使用json_decode
)获取它。
So in JavaScript you can write: 因此,您可以在JavaScript中编写:
var data = {
id: $scope.user.id,
profiles: 2,
user: "John",
color: "blue"
};
And in PHP receive: 并在PHP中接收:
$_POST['id'], $_POST['profiles'], $_POST['user'] ....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.