从cakePHP控制器检索json数组

时间:2022-10-08 09:25:59

I want to return a JSON array from a cakePHP controller. I effectively have a jquery click event which should send either a post, ajax or get call to the controller (specified with URL) and that controller should just return the array. This makes sense to me because I will not create a view file, I literally send the response to the controller and I can set the header, echo the json array and possibly just exit.

我想从cakePHP控制器返回一个JSON数组。我实际上有一个jquery click事件,它应该发送一个post,ajax或get调用控制器(用URL指定),该控制器应该只返回数组。这对我来说很有意义,因为我不会创建一个视图文件,我会将响应发送到控制器,我可以设置标头,回显json数组,可能只是退出。

My output only says "Array" on console, and does not echo out any parameters in the array. Any ideas?

我的输出只在控制台上显示“Array”,并且不会回显数组中的任何参数。有任何想法吗?

// jQuery code:
$("selector").click(function() {
      $.post("/controller/view/param1/param2/",function(data) {
         console.log(data);
      } 
}

// code in my controller:
public function view($param1 = false, $param2 = false) {
       $array = array("Name" => "John");
       header("Content-type: application/json");
       echo $array;
      exit;
}

EDIT: Found the solution - the echo $array must be echo json_encode($array)

编辑:找到解决方案 - echo $数组必须是echo json_encode($ array)

1 个解决方案

#1


3  

public function view($param1 = false, $param2 = false) {
       $array = array("Name" => "John");
       header("Content-type: application/json"); // not necessary
       echo json_encode($array);
      exit;
}

#1


3  

public function view($param1 = false, $param2 = false) {
       $array = array("Name" => "John");
       header("Content-type: application/json"); // not necessary
       echo json_encode($array);
      exit;
}