Yii2 pjax只是第一次使用

时间:2016-02-07 19:42:04

标签: php yii2 pjax

我正在使用带有Yii2的pjax,我遇到了pjax的问题​​。 所有脚本只在第一次发送pjax请求并更新表内容,脚本和pjax后才能正常工作。如果删除行$.pjax.reload({container:'#products-table'});,则所有脚本都正常工作。而且我也找到了这个解决方案(Yii2 Pjax and ActiveForm beforeSubmit not working after reload?):“$(document).on('ready pjax:success', function(){ // to do });”并且工作正常但是在添加更多jquery代码后它再次停止工作。如果有人遇到同样的问题,请与解决方案分享。谢谢!

$(document).on('ready pjax:success', function(){

    $(".product-edit-submit").on('click', function(){
            $.ajax({
                type : "POST",
                url : editUrl,
                data: {
                    id: this.id,
                    productName: productName,
                    productCost: productCost,
                    _csrf: csfr
                },
                success  : function(response) {
                    $.pjax.reload({container:'#products-table'});
                },
                error : function(response){
                    console.log(response);
                }
            });
            return false;

        });
    });

查看:

<?php Pjax::begin(['id' => 'products-table']); ?>
        <table class="table table-hover table-striped">
        .......
        </table>
<?php Pjax::end(); ?>

3 个答案:

答案 0 :(得分:0)

如果您的代码在添加额外库后停止,请尝试在视图中注册它以确保它将在包含所有库后执行:

<?php
$js = <<< 'JAVASCRIPT'
$(document).on('ready pjax:success', function(){

$(".product-edit-submit").on('click', function(){
        $.ajax({
            type : "POST",
            url : editUrl,
            data: {
                id: this.id,
                productName: productName,
                productCost: productCost,
                _csrf: csfr
            },
            success  : function(response) {
                $.pjax.reload({container:'#products-table'});
            },
            error : function(response){
                console.log(response);
            }
        });
        return false;

    });
});
JAVASCRIPT;
$this->registerJs($js,\yii\web\View::POS_READY);

答案 1 :(得分:0)

我找到了第二次脚本没有触发的原因。 我把脚本放在$(document).on('ready pjax:success', function(){ //code });之外。将其放入pjax:success内后,所有脚本都会再次运行。谢谢!

答案 2 :(得分:0)

只需更改此行$(".product-edit-submit").on('click', function(){

即可

to:

 $(document).on('click', '.product-edit-submit', function () {

然后它会起作用

相关问题