从CakePHP的控制器检索JSON数组 [英] Retrieving a json array from a cakePHP controller

查看:245
本文介绍了从CakePHP的控制器检索JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个CakePHP的控制器返回一个JSON数组。我有效有哪些应该发送任后,阿贾克斯或获取打电话给控制器(以URL指定)和控制器应该只是返回数组jQuery的单击事件。这对我来说很有意义,因为我不会创建一个视图文件,我硬是响应发送到控制器,我可以设置标题,呼应JSON数组,并可能只是退出。

我的输出只说在控制台上的阵列,并没有呼应出数组中的任何参数。任何想法?

  // jQuery的code:
$(选择)。点击(函数(){
      $。员额(/控制器/视图/参数1 /参数2 /,功能(数据){
         的console.log(数据);
      }
}

// code在我的控制器:
公共职能视图($参数1 =假,$参数2 = FALSE){
       $阵列=阵列(名称=>中约翰);
       标题(内容类型:应用程序/ JSON);
       回声$阵列;
      出口;
}
 

编辑:找到了解决办法 - 在回声$阵列必须是回声json_en code($阵列)

解决方案

 公共职能视图($参数1 =假,$参数2 = FALSE){
       $阵列=阵列(名称=>中约翰);
       标题(内容类型:应用程序/ JSON); // 不必要
       回声json_en code($阵列);
      出口;
}
 

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)

解决方案

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

这篇关于从CakePHP的控制器检索JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆