Whenever you need to output json or xml content you can use those special views. Normally BEdita apps automatically use the right View through ResponseHandler component but you can use them whenever you want: for example if you have disabled the ResponseHandler (not recommended) or if you want to force some output.
To use those views setup them in your controller like
$this->view = 'Json';
or
$this->view = 'Xml';
Those views check if a special key named "_serialize" is in viewVars and if so serialize all viewVars found in "_serialize" to present the payload to client.
For example:
$this->view = 'Json'; $this->set('section', $this->Section->find('all')); $this->set('otherData', array(...)); $this->set('_serialize', array('section', 'otherData'));
will output the json_encode()
of View::viewVars['section']
and View::viewVars['otherData']
.
Here a frontend app example where ResponseHandler is disabled and json response is handled manually
class PagesController extends AppController { public $components = array( 'ResponseHandler' => array('enabled' => false) ); public function myMethod() { $this->view = 'Json'; $this->RequestHandler->respondAs('json'); $this->set('object', $this->loadObj('nick-object'); $this->set('_serialize', array('object')); } }
If no "_serialize" view var is found the JsonView or XmlView will try to render a standard view file. It is useful for example if you need to manipulate data before serializing it. Removing "_serialize" from above example you need to add a view file named my_method.tpl
in views/pages/ folder
and manually build the json you want to output.
XmlView accepts another special key named "_rootNode" that you can define to explicit the xml root tag. If it's not defined the < response >< /response >
tag is used.
Example:
$this->set(array( 'object' => $object, '_serialize' => 'object', '_rootNode' => 'object' ));
will output $object
in xml format using object tag as root
while
$this->set(array( 'object' => $object, '_serialize' => 'object' ));
will output