AjaxView.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. App::uses('View', 'View');
  3. /**
  4. * A view to handle AJAX requests.
  5. *
  6. * Expects all incoming requests to be of extension "json" and that the expected result
  7. * will also be in JSON format.
  8. *
  9. * @author Mark Scherer
  10. * @license MIT
  11. */
  12. class AjaxView extends View {
  13. /**
  14. * The subdirectory. AJAX views are always in ajax.
  15. *
  16. * @var string
  17. */
  18. public $subDir = 'ajax';
  19. /**
  20. * Name of layout to use with this View.
  21. *
  22. * @var string
  23. */
  24. public $layout = false;
  25. /**
  26. * Constructor
  27. *
  28. * @param Controller $controller
  29. */
  30. public function __construct(Controller $controller = null) {
  31. parent::__construct($controller);
  32. // Unfortunately, layout gets overwritten via passed Controller attribute
  33. if ($this->layout === 'default' || $this->layout === 'ajax') {
  34. $this->layout = false;
  35. }
  36. if (isset($controller->response) && $controller->response instanceof CakeResponse) {
  37. $controller->response->type('json');
  38. }
  39. }
  40. /**
  41. * Renders a JSON view.
  42. *
  43. * @param string $view The view being rendered.
  44. * @param string $layout The layout being rendered.
  45. * @return string The rendered view.
  46. */
  47. public function render($view = null, $layout = null) {
  48. $response = array(
  49. 'error' => null,
  50. 'content' => null,
  51. );
  52. if ($view !== false && $this->_getViewFileName($view)) {
  53. $response['content'] = parent::render($view, $layout);
  54. }
  55. if (isset($this->viewVars['_serialize'])) {
  56. $response = $this->_serialize($response, $this->viewVars['_serialize']);
  57. }
  58. return json_encode($response);
  59. }
  60. /**
  61. * Serialize view vars
  62. *
  63. * @param array $serialize The viewVars that need to be serialized
  64. * @return string The serialized data
  65. */
  66. protected function _serialize($response, $serialize) {
  67. if (is_array($serialize)) {
  68. foreach ($serialize as $alias => $key) {
  69. if (is_numeric($alias)) {
  70. $alias = $key;
  71. }
  72. if (array_key_exists($key, $this->viewVars)) {
  73. $response[$alias] = $this->viewVars[$key];
  74. }
  75. }
  76. } else {
  77. $response[$serialize] = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
  78. }
  79. return $response;
  80. }
  81. }