Yii2 pjax重装显示响应

时间:2018-03-12 11:50:02

标签: javascript php ajax yii2 pjax

在我的网站上,我使用ajax提交数据,使用pjax重新上载列表视图。我第一次提交表单时工作正常,保存并重新上传列表视图,第二次保存数据但不重新加载列表视图,它显示来自操作{"success":true,"id":68}的响应。有人可以看一下吗?

动作

public function actionReply()
{
    $model = new ReplyForm();
    $response = [];

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {

        if ($model->save()) {
            $response['success'] = true;
            $response['id'] = $model->id;
        }

    } else {
        $response['success'] = false;
    }

    Yii::$app->response->format = Response::FORMAT_JSON;
    return $response;
}
视图文件中的

脚本

$(document).ready(function () {
    var $form = $('form#reply-form');

    $form.on('beforeSubmit', function (event) {

        var data = $form.serialize();

        $.ajax({             
            type: 'POST',
            url: $form.attr('action'),
            data: data,
            dataType: 'json',
            success: function (d) {
                if(d.success === true){
                    //$.pjax.reload({container: '#comments', async: false});

                    $.pjax.reload('#comments', {timeout: false});
                    $form.trigger('reset');
                }else {
                    alert('error');
                }
            }
        });

        return false;
    });
});

并查看表单文件

<div class="page-form">
<?php $form = ActiveForm::begin([
    'id' => 'reply-form',
    'action' => ['comment/reply'],
    'options' => ['data-pjax' => true],
]); ?>

<?= $form->field($model, 'content')->textarea(['maxlength' => true, 'class' => 'form-control', 'rows' => 3]) ?>
<?= $form->field($model, 'item_id')->hiddenInput()->label(false) ?>
<?= $form->field($model, 'parent_id')->hiddenInput()->label(false) ?>

<div class="form-group">
    <?= Html::submitButton('Wyślij', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

查看评论文件

<?php Pjax::begin(['id' => 'comments']) ?>
                    <?= ListView::widget([
                        'dataProvider' => $commentDataProvider,
                        'summary' => false,
                        'itemView' => '_comment',
                        'options' => [
                            'tag' => 'div',
                            'class' => 'block-post-comments',
                        ],
                        'pager' => [
                            'class' => LinkPager::class
                        ]
                    ]); ?>
<?php Pjax::end() ?>

0 个答案:

没有答案