| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?xml version="1.0" encoding="UTF-8"?>
- <!-- Reviewed: no -->
- <sect3 id="zend.view.helpers.initial.json">
- <title>JSON Helper</title>
- <para>
- When creating views that return JSON, it's important to also set the
- appropriate response header. The JSON view helper does exactly that. In
- addition, by default, it disables layouts (if currently enabled), as
- layouts generally aren't used with JSON responses.
- </para>
- <para>
- The JSON helper sets the following header:
- </para>
- <programlisting language="text"><![CDATA[
- Content-Type: application/json
- ]]></programlisting>
- <para>
- Most AJAX libraries look for this header when parsing responses to
- determine how to handle the content.
- </para>
- <para>
- Usage of the JSON helper is very straightforward:
- </para>
- <programlisting language="php"><![CDATA[
- <?php echo $this->json($this->data) ?>
- ]]></programlisting>
- <note>
- <title>Keeping layouts and enabling encoding using Zend_Json_Expr</title>
- <para>
- Each method in the JSON helper accepts a second, optional argument.
- This second argument can be a boolean flag to enable or disable
- layouts, or an array of options that will be passed to
- <classname>Zend_Json::encode()</classname> and used internally to encode data.
- </para>
- <para>
- To keep layouts, the second parameter needs to be boolean
- <constant>TRUE</constant>. When the second parameter is an array, keeping
- layouts can be achieved by including a <code>keepLayouts</code> key
- with a value of a boolean <constant>TRUE</constant>.
- </para>
- <programlisting language="php"><![CDATA[
- // Boolean true as second argument enables layouts:
- echo $this->json($this->data, true);
- // Or boolean true as "keepLayouts" key:
- echo $this->json($this->data, array('keepLayouts' => true));
- ]]></programlisting>
- <para>
- <classname>Zend_Json::encode</classname> allows the encoding of native JSON
- expressions using <classname>Zend_Json_Expr</classname> objects. This option
- is disabled by default. To enable this option, pass a boolean
- <constant>TRUE</constant> to the <code>enableJsonExprFinder</code> key of
- the options array:
- </para>
- <programlisting language="php"><![CDATA[
- <?php echo $this->json($this->data, array(
- 'enableJsonExprFinder' => true,
- 'keepLayouts' => true,
- )) ?>
- ]]></programlisting>
- </note>
- </sect3>
- <!--
- vim:se ts=4 sw=4 et:
- -->
|