Zend_View-Helpers-Json.xml 2.7 KB

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