Returning JSON in a Zend Controller’s Action

There are three basic ways that you can achieve that. First of all what’s the task? You’ve an array, either from a database result or whatever, and you encode it JSON with Zend_Json::encode($array)php

// IndexController.php class IndexController extends Zend_Controller_Action{ 	public function indexAction() 	{ 		$data = array(...);  
		$this->view->data = Zend_Json::encode($data);	
	}	}

The result in general is a specially formatted string. So you can simply set it up to a view member variable and pass it to the view.html

// index/index.phtml echo $this->data

In that case you’ve a .phtml file to maintain, so lets just return the string and 「setNoRender」 the view in our second try.json

// IndexController.php class IndexController extends Zend_Controller_Action{ 	public function indexAction() 	{ 		$data = array(...);  
		echo Zend_Json::encode($data);	
 
		$this->_helper->viewRenderer->setNoRender(true); 	}	}

Actually this is pretty much the most clear solution, but actually you can output the JSON string and simply exit() as it’s shown in our third example.post

// IndexController.php class IndexController extends Zend_Controller_Action{ 	public function indexAction() 	{ 		$data = array(...);  
		echo Zend_Json::encode($data);	
 
		exit(); 	}	}

Which one is to be used is up to the developer’s choice, mine is the third one as it’s the minimal one.this

Related posts:spa

  1. JSON and Zend Framework? – Zend_Json
  2. Bind Zend Action with Non-Default View
  3. Returning JSON in a Zend Controller’s Action – Part 2
相關文章
相關標籤/搜索