Pjax.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\widgets;
  8. use Yii;
  9. use yii\base\Widget;
  10. use yii\helpers\ArrayHelper;
  11. use yii\helpers\Html;
  12. use yii\helpers\Json;
  13. use yii\web\Response;
  14. /**
  15. * Pjax is a widget integrating the [pjax](https://github.com/yiisoft/jquery-pjax) jQuery plugin.
  16. *
  17. * Pjax only deals with the content enclosed between its [[begin()]] and [[end()]] calls, called the *body content* of the widget.
  18. * By default, any link click or form submission (for those forms with `data-pjax` attribute) within the body content
  19. * will trigger an AJAX request. In responding to the AJAX request, Pjax will send the updated body content (based
  20. * on the AJAX request) to the client which will replace the old content with the new one. The browser's URL will then
  21. * be updated using pushState. The whole process requires no reloading of the layout or resources (js, css).
  22. *
  23. * You may configure [[linkSelector]] to specify which links should trigger pjax, and configure [[formSelector]]
  24. * to specify which form submission may trigger pjax.
  25. *
  26. * You may disable pjax for a specific link inside the container by adding `data-pjax="0"` attribute to this link.
  27. *
  28. * The following example shows how to use Pjax with the [[\yii\grid\GridView]] widget so that the grid pagination,
  29. * sorting and filtering can be done via pjax:
  30. *
  31. * ```php
  32. * use yii\widgets\Pjax;
  33. *
  34. * Pjax::begin();
  35. * echo GridView::widget([...]);
  36. * Pjax::end();
  37. * ```
  38. *
  39. * @author Qiang Xue <qiang.xue@gmail.com>
  40. * @since 2.0
  41. */
  42. class Pjax extends Widget
  43. {
  44. /**
  45. * @var array the HTML attributes for the widget container tag. The following special options are recognized:
  46. *
  47. * - `tag`: string, the tag name for the container. Defaults to `div`
  48. * This option is available since version 2.0.7.
  49. * See also [[\yii\helpers\Html::tag()]].
  50. *
  51. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  52. */
  53. public $options = [];
  54. /**
  55. * @var string|false the jQuery selector of the links that should trigger pjax requests.
  56. * If not set, all links within the enclosed content of Pjax will trigger pjax requests.
  57. * If set to false, no code will be registered to handle links.
  58. * Note that if the response to the pjax request is a full page, a normal request will be sent again.
  59. */
  60. public $linkSelector;
  61. /**
  62. * @var string|false the jQuery selector of the forms whose submissions should trigger pjax requests.
  63. * If not set, all forms with `data-pjax` attribute within the enclosed content of Pjax will trigger pjax requests.
  64. * If set to false, no code will be registered to handle forms.
  65. * Note that if the response to the pjax request is a full page, a normal request will be sent again.
  66. */
  67. public $formSelector;
  68. /**
  69. * @var string The jQuery event that will trigger form handler. Defaults to "submit".
  70. * @since 2.0.9
  71. */
  72. public $submitEvent = 'submit';
  73. /**
  74. * @var bool whether to enable push state.
  75. */
  76. public $enablePushState = true;
  77. /**
  78. * @var bool whether to enable replace state.
  79. */
  80. public $enableReplaceState = false;
  81. /**
  82. * @var int pjax timeout setting (in milliseconds). This timeout is used when making AJAX requests.
  83. * Use a bigger number if your server is slow. If the server does not respond within the timeout,
  84. * a full page load will be triggered.
  85. */
  86. public $timeout = 1000;
  87. /**
  88. * @var bool|int how to scroll the page when pjax response is received. If false, no page scroll will be made.
  89. * Use a number if you want to scroll to a particular place.
  90. */
  91. public $scrollTo = false;
  92. /**
  93. * @var array additional options to be passed to the pjax JS plugin. Please refer to the
  94. * [pjax project page](https://github.com/yiisoft/jquery-pjax) for available options.
  95. */
  96. public $clientOptions;
  97. /**
  98. * {@inheritdoc}
  99. * @internal
  100. */
  101. public static $counter = 0;
  102. /**
  103. * {@inheritdoc}
  104. */
  105. public static $autoIdPrefix = 'p';
  106. /**
  107. * {@inheritdoc}
  108. */
  109. public function init()
  110. {
  111. parent::init();
  112. if (!isset($this->options['id'])) {
  113. $this->options['id'] = $this->getId();
  114. }
  115. if ($this->requiresPjax()) {
  116. ob_start();
  117. ob_implicit_flush(false);
  118. $view = $this->getView();
  119. $view->clear();
  120. $view->beginPage();
  121. $view->head();
  122. $view->beginBody();
  123. if ($view->title !== null) {
  124. echo Html::tag('title', Html::encode($view->title));
  125. }
  126. } else {
  127. $options = $this->options;
  128. $tag = ArrayHelper::remove($options, 'tag', 'div');
  129. echo Html::beginTag($tag, array_merge([
  130. 'data-pjax-container' => '',
  131. 'data-pjax-push-state' => $this->enablePushState,
  132. 'data-pjax-replace-state' => $this->enableReplaceState,
  133. 'data-pjax-timeout' => $this->timeout,
  134. 'data-pjax-scrollto' => $this->scrollTo,
  135. ], $options));
  136. }
  137. }
  138. /**
  139. * {@inheritdoc}
  140. */
  141. public function run()
  142. {
  143. if (!$this->requiresPjax()) {
  144. echo Html::endTag(ArrayHelper::remove($this->options, 'tag', 'div'));
  145. $this->registerClientScript();
  146. return;
  147. }
  148. $view = $this->getView();
  149. $view->endBody();
  150. $view->endPage(true);
  151. $content = ob_get_clean();
  152. // only need the content enclosed within this widget
  153. $response = Yii::$app->getResponse();
  154. $response->clearOutputBuffers();
  155. $response->setStatusCode(200);
  156. $response->format = Response::FORMAT_HTML;
  157. $response->content = $content;
  158. $response->headers->setDefault('X-Pjax-Url', Yii::$app->request->url);
  159. $response->send();
  160. Yii::$app->end();
  161. }
  162. /**
  163. * @return bool whether the current request requires pjax response from this widget
  164. */
  165. protected function requiresPjax()
  166. {
  167. $headers = Yii::$app->getRequest()->getHeaders();
  168. return $headers->get('X-Pjax') && explode(' ', $headers->get('X-Pjax-Container'))[0] === '#' . $this->options['id'];
  169. }
  170. /**
  171. * Registers the needed JavaScript.
  172. */
  173. public function registerClientScript()
  174. {
  175. $id = $this->options['id'];
  176. $this->clientOptions['push'] = $this->enablePushState;
  177. $this->clientOptions['replace'] = $this->enableReplaceState;
  178. $this->clientOptions['timeout'] = $this->timeout;
  179. $this->clientOptions['scrollTo'] = $this->scrollTo;
  180. if (!isset($this->clientOptions['container'])) {
  181. $this->clientOptions['container'] = "#$id";
  182. }
  183. $options = Json::htmlEncode($this->clientOptions);
  184. $js = '';
  185. if ($this->linkSelector !== false) {
  186. $linkSelector = Json::htmlEncode($this->linkSelector !== null ? $this->linkSelector : '#' . $id . ' a');
  187. $js .= "jQuery(document).pjax($linkSelector, $options);";
  188. }
  189. if ($this->formSelector !== false) {
  190. $formSelector = Json::htmlEncode($this->formSelector !== null ? $this->formSelector : '#' . $id . ' form[data-pjax]');
  191. $submitEvent = Json::htmlEncode($this->submitEvent);
  192. $js .= "\njQuery(document).on($submitEvent, $formSelector, function (event) {jQuery.pjax.submit(event, $options);});";
  193. }
  194. $view = $this->getView();
  195. PjaxAsset::register($view);
  196. if ($js !== '') {
  197. $view->registerJs($js);
  198. }
  199. }
  200. }