Well, when looking to simplify some actions and views that present JSON data to pass back from AJAX queries, I was pointed in the direction of the ContextSwitch action helper. One of the default contexts available, is the JSON context, which will disable all layout, and output serialized versions of any variables found in the view. This sounded perfect for what I wanted to achieve.
Basically, you tell the controller which additional contexts should be available in the init function of the controller, and then pass format=<context> to tell the action to render the page in that context. The code is:
public function init() { $contextSwitch = $this->_helper->getHelper('contextSwitch'); $contextSwitch->addActionContext('saverss, 'json') ->initContext(); }
You can then get anything set into a view variable json encoded by passing the querystring parameter format=json (or /format/json/), so:
public function saverssAction() { $this->view->response = array('x', 'y', 'z'); }
Returns the JSON:
{"controller":"mediaman","response":["x","y","z"]}
This is really helpful when you have a number of actions that are called using AJAX from your front-end. Thanks to Bittarman in the #zftalk channel for the heads up.
More Reading…