仅在重定向时在 pjax 中推送状态

Pushstate in pjax only when redirecting

在我的一个页面中,我有一个由 pjax 处理的 link。基本上用户点击一个项目,这个项目变成"checked"(并保存在数据库中)。

我已经为这些请求禁用了 pushState,因为它没有意义,用户有效地停留在同一页面,所以 counter-intuitive 更改 url。

但是,有时此 pjax 请求会导致重定向到登录页面(当用户未登录时)。这是我真正需要 pushState 工作的时候,并不是因为我一开始就禁用了它。

是否可以配置 pjax,使正常响应在没有 pushState 的情况下工作,但重定向响应(使用 X-Pjax-Url header 完成)do 执行 pushState?

使用当前功能无法做到这一点。我已经为 pjax 添加了两个选项,我的 PR 已经被 pjax 的 yii2 分支接受。所以,事不宜迟:

https://github.com/yiisoft/jquery-pjax

//pushRedirect - Whether to pushState the URL for redirects. Defaults to false.
//replaceRedirect - Whether to replaceState the URL for redirects. Defaults to true.

// ...

jQuery(document).pjax("#example_selector", {
  "push": false,
  "replace": false,
  "pushRedirect": true,
  "replaceRedirect": false
});

使用 linkSelector 指定哪些链接触发 pjax 调用

<?php Pjax::begin([
    'enablePushState' => false, // don't change the Browser URL
    'linkSelector' => 'pjax-btn', // pjax links that 
]); ?>

<?= GridView::widget([
    //...
    [ // no pjax, normal linl
        'label' => 'link with state replace',
        'format' => 'raw',
        'value' => function ($model, $key, $index, $column) {
            return Html::a($model->title, Url::to(['/controllet/action', 'id' => $model->id]));
        }
    ],
    [
        'class' => 'yii\grid\ActionColumn',
        //'class' => 'common\widgets\ActionColumn',
        'template' => '{toggle} {view} {update} {delete}',
        'buttons' => [
            'toggle' => function ($url, $model, $key) {
                $options = [
                    'title' => 'Privacy',
                    'aria-label' => 'Privacy',
                    'class' => 'pjax-btn', // no state replacement, load with pjax
                ];
                $icon = Html::tag('span', '', ['class' => 'glyphicon glyphicon-check']);
                return Html::a($icon, $url, $options);
            },
        ]
    ]]) ?>
 <?php Pjax::end(); ?>