yii2 how to use pjax when hyperlink is not in pjax

♀尐吖头ヾ 提交于 2019-12-02 01:01:58

问题


To use pjax in yii2, just like:

<?php Pjax::begin(); ?>
<?= Html::a("Refresh", ['site/index'], ['class' => 'btn btn-lg btn-primary']);?>
<h1>Current time: <?= $time ?></h1>
<?php Pjax::end(); ?>

but what if the hyperlink is not in the <?php Pjax::begin(); ?> <?php Pjax::end(); ?>, just like:

<nav>
<a href="">Click to refresh</a>
</nav>

<?php Pjax::begin(); ?>
<h1>Current time: <?= $time ?></h1>
<?php Pjax::end(); ?>

回答1:


PJAX has timeout option. If PJAX not obtain AJAX response during this timeout, it will perform full page reload. Use following JS snippet:

$.pjax.defaults.timeout = false;       // For JS use case yor should manual override default timeout.
$.pjax.reload({container: '#pjaxId'});

or more short snippet:

$.pjax.reload('#pjaxId', {timeout : false});

Moreover in my projects I use overrided version of Pjax:

/**
 * Custom Pjax with incremented timeout.
 * JS for Pjax updating:
 *  <code>
 *      $.pjax.defaults.timeout = false;             // For JS use case yor should manual override default timeout.
 *      $.pjax.reload({container: '#pjaxId'});
 *
 *      // OR
 *      $.pjax.reload('#pjaxId', {timeout : false});
 *
 *      // OR for gridview with search filters
 *      $('.grid-view').yiiGridView('applyFilter'); // Thats true only if you have search Filters
 *  </code>
 *
 * Note: In more cases ID of widget should be static, because widgetId is autoincremented and browser version of page may be not up-to-date.
 */
class Pjax extends \yii\widgets\Pjax
{
    /**
     * @var int Timeout {@link \yii\widgets\Pjax::$timeout}.
     *          For JS use case yor should manual override defaults (  $.pjax.defaults.timeout = false;  ).
     */
    public $timeout = 30000;
}



回答2:


Just like this:

<?= Html::a("Refresh", ['site/index'], ['class' => 'btn btn-lg btn-primary']); ?>
<?php Pjax::begin(); ?>

<h1>Current time: <?= $time ?></h1>
<?php Pjax::end(); ?>

it worked!




回答3:


I think this can solve your problem.

<span class="my-btn  btn btn-lg btn-danger">refresh</span>
<a href="javascript:function() { return false; }" class="my-btn btn btn-lg btn-primary"> refresh a</a>

<?php

$this->registerJs(
   '$("document").ready(function(){ 
        $(".my-btn").on("click", function() {
            $.pjax.reload({container:"#greet"});
        });
    });'
);
?>
<?php yii\widgets\Pjax::begin(['id'=>'greet']); ?>

<h1>Current time: <?= time() ?></h1>
<?php yii\widgets\Pjax::end(); ?>


来源:https://stackoverflow.com/questions/39139958/yii2-how-to-use-pjax-when-hyperlink-is-not-in-pjax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!