1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect3 id="zend.view.helpers.initial.json">
4 <title>JSON Helper</title>
7 When creating views that return <acronym>JSON</acronym>, it's important to also set the
8 appropriate response header. The <acronym>JSON</acronym> view helper does exactly that. In
9 addition, by default, it disables layouts (if currently enabled), as
10 layouts generally aren't used with <acronym>JSON</acronym> responses.
14 The <acronym>JSON</acronym> helper sets the following header:
17 <programlisting language="text"><![CDATA[
18 Content-Type: application/json
22 Most <acronym>AJAX</acronym> libraries look for this header when parsing responses to
23 determine how to handle the content.
27 Usage of the <acronym>JSON</acronym> helper is very straightforward:
30 <programlisting language="php"><![CDATA[
31 <?php echo $this->json($this->data) ?>
35 <title>Keeping layouts and enabling encoding using Zend_Json_Expr</title>
38 Each method in the <acronym>JSON</acronym> helper accepts a second, optional argument.
39 This second argument can be a boolean flag to enable or disable
40 layouts, or an array of options that will be passed to
41 <methodname>Zend_Json::encode()</methodname> and used internally to encode data.
45 To keep layouts, the second parameter needs to be boolean
46 <constant>TRUE</constant>. When the second parameter is an array, keeping
47 layouts can be achieved by including a <property>keepLayouts</property> key
48 with a value of a boolean <constant>TRUE</constant>.
51 <programlisting language="php"><![CDATA[
52 // Boolean true as second argument enables layouts:
53 echo $this->json($this->data, true);
55 // Or boolean true as "keepLayouts" key:
56 echo $this->json($this->data, array('keepLayouts' => true));
60 <classname>Zend_Json::encode</classname> allows the encoding of native
61 <acronym>JSON</acronym> expressions using <classname>Zend_Json_Expr</classname> objects.
62 This option is disabled by default. To enable this option, pass a boolean
63 <constant>TRUE</constant> to the <property>enableJsonExprFinder</property> key of
67 <programlisting language="php"><![CDATA[
68 <?php echo $this->json($this->data, array(
69 'enableJsonExprFinder' => true,
70 'keepLayouts' => true,