JSON output for Zend Framework

In the controller, I generate a special form by ID passed from AJAX. The form output is JSON. The form is created finely. But my problem is to show this JSON. How?

Thanks.

+6
json ajax php zend-framework
source share
5 answers

In the controller ( http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.json ):

$this->getHelper('json')->sendJson(array( 'param1' => 'v1' 'param2' => 'v2' )); 

In the field of view ( http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.initial.json ):

 <?php echo $this->json(array( 'param1' => 'v1' 'param2' => 'v2' )); ?> 
+23
source share

json is a coded string containing js style vars, if you need to access a member in that string, you need a json_decode string to

 $result = json_decode($jsonString); 

but note that json processes an associative php array, such as a php object ... so if you pass an array, you can access it as $ result-> memberReference, not $ result ['memberReference'];

+2
source share

The easiest way is to stop viewing:

 function jsonAction () { .... print $json; exit; } 

Also see http://pl.php.net/json_encode if you don't already have a JSON string.

+1
source share

You can use the Zend class

 $sData = Zend_Json::encode($aArray); 

Or you can use an advanced script, for example:

 $data = array( 'onClick' => new Zend_Json_Expr('function() {' . 'alert("I am a valid javascript callback ' . 'created by Zend_Json"); }'), 'other' => 'no expression', ); $jsonObjectWithExpression = Zend_Json::encode($data,false, array('enableJsonExprFinder' => true) ); 
+1
source share

The best way to do this, in my opinion, is to assign one controller as your json output, then you can do this:

 class Api_IndexController extends Zend_Controller_Action { public function init() { $this->data = array(); } public function preDispatch() { $this->variables = $this->_getAllParams(); } public function postDispatch() { $this->_helper->json($this->data); } public function __call($name, $args) { return; } public function forumAction () { $this->mapper = new ORM_Model_Mapper_Forum(); $this->model = new ORM_Model_Forum(); $this->dbTable = new ORM_Model_DbTable_Forum(); if (isset($this->variables['id']) && is_numeric($this->variables['id'])) { $output = $this->model->find($this->variables['id']); if ($output->id == null) { return $this->_setError(404); } } else { $output = $this->mapper->fetchAllToArray(); } $this->data = $output; } private function _setError($code=500) { $this->data = array('error' => $code); } } 
+1
source share

All Articles