JSON
JSON responses are rapidly becoming the response of choice when dealing
with AJAX requests that expect dataset responses;
JSON can be immediately parsed on the client-side, leading to quick
execution.
The JSON action helper does several things:
Disables layouts if currently enabled.
Optionally, an array of options to pass as the second argument
to Zend_Json::encode(). This array of options
allows enabling layouts and encoding using
Zend_Json_Expr.
_helper->json($data, array('enableJsonExprFinder' => true));
]]>
Disables the ViewRenderer if currently enabled.
Sets the 'Content-Type' response header to 'application/json'.
By default, immediately returns the response, without waiting
for the action to finish execution.
Usage is simple: either call it as a method of the helper broker, or
call one of the methods encodeJson() or
sendJson():
_helper->json($data);
// or...
$this->_helper->json->sendJson($data);
// or retrieve the json:
$json = $this->_helper->json->encodeJson($data);
}
}
]]>
Keeping Layouts
If you have a separate layout for JSON responses -- perhaps to wrap
the JSON response in some sort of context -- each method in the
JSON helper accepts a second, optional argument: a flag to enable or
disable layouts. Passing a boolean TRUE value will keep
layouts enabled:
_helper->json($data, true);
]]>
Optionally, you can pass an array as the second parameter. This
array may contain a variety of options, including the
keepLayouts option:
_helper->json($data, array('keepLayouts' => true);
]]>
Enabling encoding using Zend_Json_Expr
Zend_Json::encode() allows the encoding of native
JSON expressions using Zend_Json_Expr
objects. This option is disabled by default. To enable this option, pass a boolean
TRUE value to the enableJsonExprFinder
option:
_helper->json($data, array('enableJsonExprFinder' => true);
]]>
If you desire to do this, you must pass an
array as the second argument. This also allows you to combine other
options, such as the keepLayouts option. All such
options are then passed to Zend_Json::encode().
_helper->json($data, array(
'enableJsonExprFinder' => true,
'keepLayouts' => true,
));
]]>