AjaxView.php 2.2 KB

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