Retrieving a json array from a cakePHP controller

会有一股神秘感。 提交于 2019-12-10 17:24:54

问题


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.

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

// 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)


回答1:


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


来源:https://stackoverflow.com/questions/10188157/retrieving-a-json-array-from-a-cakephp-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!