Yii2在Ajax之后更新Listview的DataProvider

时间:2016-10-26 12:28:56

标签: php yii2

当我通过Ajax提交表单时,我尝试未成功更新列表视图的DataProvider。它在我没有ajax提交时工作,但刷新页面。我想在不刷新页面的情况下这样做。我不知道下面代码中究竟出现了什么问题:

以下是表单和列表视图:

jobs.php

...

<div style="background-color: white;">

<div class="job_quick_search_container">

    <?php $form = ActiveForm::begin([
        'id' => 'quick_search_form',
        'enableAjaxValidation'=>false,
        'enableClientValidation'=>true,
        'options' => ['class' => 'form-horizontal', 
                      'onkeypress'=>" if(event.keyCode == 13){ searchJob(); }" 
                     ],
    ]); ?>

    <table style="width:100%">
        <colgroup>
            <col style="width:20%">
            <col style="width:20%">
            <col style="width:20%">
            <col style="width:40%">
        </colgroup>

        <tr>    
            <td style="padding-right: 50px;">
                 <?= $form->field($jobCompanyCategorySearchModel, 'ccCategory')->dropDownList( ArrayHelper::map(Companycategory::find()->all(),'ccID', 'ccCategory'), ['prompt'=>'Select a category'] ) 
                 ?>                 
            </td>

            <td style="padding-right: 50px;">
                <?= $form->field($jobUserSearchModel, 'uCountry')->dropDownList( ArrayHelper::map(User::find()->all(),
                                                                     'uCountry', 'uCountry'),
                                                                     ['prompt'=>'Select a country'] ) 
                ?>
            </td>

            <td style="padding-right: 50px;">
                <?= $form->field($jobUserSearchModel, 'uCompanyName')->dropDownList( ArrayHelper::map(User::find()->all(),
                                                                     'uCompanyName', 'uCompanyName'),
                                                                     ['prompt'=>'Select a company'] ) 
                ?>
            </td>

            <td>


                <div class="form-group">
                   <?= Html::Button('Find a job', ['class' => 'btn btn-primary', 
                                                   'onclick' => 'searchJob();',  
                                                   'style' => 'font-size:18px']) ?>
                </div>
            </td>
        </tr>

    </table>

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

</div>


<table style="width:100%">
    <colgroup>
        <col style="width:65%">
        <col style="width:35%">
    </colgroup>

    <tr>
        <td>
             //This partial view contains the listview
            <?= $this->render( 'jobs_partial_view', ['dataProvider'=> $dataProvider] ); ?>

        </td>
  ...

部分视图: jobs_partial_view.php

<?php
   use yii\widgets\ListView;
?>

<div class="jobs_listView_container">

    <?= 
        ListView::widget([

            'dataProvider' => $dataProvider,
            'options' => [
                            'tag' => 'div',
                            'class' => 'list_jobs_profile',
                            'id' => 'list_jobs_profile',
                        ],
            'layout' => "{items}\n{pager}",

            'itemView' => function ($model, $key, $index, $widget) {
                return $this->render('_job_view',['model' => $model]);
            },

            'itemOptions' => [
                'tag' => false,
            ],

            'pager' => [
                'firstPageLabel' => 'first',
                'lastPageLabel' => 'last',
                'nextPageLabel' => 'next',
                'prevPageLabel' => 'previous',
                'maxButtonCount' => 3,
            ],

            'emptyText' => "Sorry, No jobs found",

        ]);
    ?>

这是使用Ajax的 Jquery函数

function searchJob(){

var seach_data_job = $("#quick_search_form").serialize();

$.ajax({
    type: 'POST',
    url: 'jobs',
    data: seach_data_job,
    dataType: 'html',

    success: function(e) {

    },

    /*

    error: function(response, status){
        console.log(response);
        console.log(status);
    }

    */
});

return false;
}

此处控制器

public function actionJobs()
{

      $jobCompanyCategorySearchModel = new JobCompanycategorySearch();
      $jobUserSearchModel = new JobUserSearch();

     if (  $jobUserSearchModel->load( Yii::$app->request->post() ) && 
          $jobCompanyCategorySearchModel->load( Yii::$app->request->post() ) ) {


        $idCategorySearch = $jobCompanyCategorySearchModel->ccCategory;
        $companyNameSearch = $jobUserSearchModel->uCompanyName;
        $companyCountrySearch = $jobUserSearchModel->uCountry;

         $dataProvider = new ActiveDataProvider([
                'query' => Jobs::find()->where(['jCategory' => $idCategorySearch])
                                       ->orderBy('jID DESC'), 
                'pagination' => ['pageSize' => 10,],
            ]);

         echo $this->renderPartial( 'jobs_partial_view', 
                                                ['jobCompanyCategorySearchModel' => $jobCompanyCategorySearchModel,
                                                 'jobUserSearchModel' => $jobUserSearchModel,
                                                 'dataProvider' => $dataProvider
                                                ] );
    } 

  else {


      $dataProvider = new ActiveDataProvider([
            'query' => Jobs::find()->orderBy('jID DESC'),  
            'pagination' => ['pageSize' => 10,],
        ]);

     return $this->render('jobs', ['jobCompanyCategorySearchModel' => $jobCompanyCategorySearchModel,
                                          'jobUserSearchModel' => $jobUserSearchModel,
                                          'dataProvider' => $dataProvider
                                          ] );
   }

       }

通过Ajax提交表单后,我在控制器中获取数据,但功能renderPartial没有使用新的dataProvider更新视图。

2 个答案:

答案 0 :(得分:2)

你可以在你的情况下使用Pjax。所以你的来自下面。

<?php \yii\widgets\Pjax::begin(['clientOptions' => ['method' => 'POST']]); ?>

    <?php $form = ActiveForm::begin([
      'id' => 'quick_search_form',
      'enableAjaxValidation'=>false,
      'enableClientValidation'=>true,
      'options' => ['class' => 'form-horizontal']
    ]); ?>
        .......
        .......
        <!-- your form htmls will goes here -->
        .......
        .......
    <?php \yii\widgets\ActiveForm::end(); ?>
    <?= $this->render( 'jobs_partial_view', ['dataProvider'=> $dataProvider] ); ?>
<?php \yii\widgets\Pjax::end(); ?>

注意:您无需为表单提交编写ajax代码。 Pjax将采用所有ajax的东西。此外,您必须将两个控制器操作 - actionJobsactionJobsearch合并为单个操作。因此,所有actionJobsearch编码都将在actionJobs内。

答案 1 :(得分:2)

最后我发现自己是我的问题的解决方案,但它可以帮助下一个读者。

数据提供者和ajax提交中的一切都很完美。之前我不知道的是,在更新Dataprovider并调用函数renderPartial()后,

 $dataProvider = new ActiveDataProvider([
    'query' => Jobs::find()->where(['jCategory' => $idCategorySearch])
                           ->orderBy('jID DESC'), 
    'pagination' => ['pageSize' => 10,],
 ]);

 echo $this->renderPartial( 'jobs_partial_view', 
                            ['jobCompanyCategorySearchModel' => $jobCompanyCategorySearchModel,
                             'jobUserSearchModel' => $jobUserSearchModel,
                             'dataProvider' => $dataProvider
                            ] );

我可以使用jQuery获取Ajax响应的视图(新的Listview)并将其加载到旧列表视图容器的html内容中:

function searchJob(){

var form = $("#quick_search_form");
var search_data_job = form.serialize();

var partialviewcontainer = $("#jobs_partial_view_container");

$.ajax({
    type: 'POST',
    url: 'jobs',
    data: search_data_job,
    dataType: 'html',

    success: function(newPartialView) {
                 partialviewcontainer.html(newPartialView);
             },

});

return false;

 }

我添加了 fadeIn fadeOut 功能,使重新加载顺畅。

自:

partialviewcontainer.html(newPartialView);

要:

 $(partialviewcontainer).fadeOut(800, function(){                      
      partialviewcontainer.html(newPartialView).fadeIn().delay(2000);
 });

希望它会有所帮助。

感谢那些试图帮助我的人。