如何使用Yii2从ajax调用填充gridview

时间:2017-12-06 05:27:53

标签: json yii2

在我的项目中,我创建了一个搜索框。当我输入内容并单击“获取信息”按钮时,我使用ajax调用在控制台窗口中获取所有信息。现在我想在yii2 gridview中填充这些数据。每个运行时的数据都不同。我想把这个数据提供给gridview的$ dataprovider是否有可能?

这里是代码 - CompaniesController.php

public function actionCompanyinfo(){     

    $text_in_search = $_GET['text_in_search'];
    $left_items_cat = ltrim($_GET['left_items_cat']);

    if($left_items_cat == "Companies"){

         $query = (new \yii\db\Query())
                ->select(['c.name', 'c.id'])
                ->from(['companies as c'])
                ->where('c.name LIKE :query') 
                ->addParams([':query'=>'%'.$text_in_search.'%'])
                ->all(); 

        $response['comapnies_matching'] = $query;
            return \yii\helpers\Json::encode([
        $response
    ]);  

    }
}

公司/ index.php的

$form = ActiveForm::begin();
 $typeahead = $form->field($model, 'name')->textInput(['maxlength' => true]);

$getinfobtn = Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ;
   ActiveForm::end();  

myjsfile.js

$("#getinfo").click(function(){
        var text_in_search = $("#companies-name").val();
        var left_items_cat = $('#left-items li.active').text();
        var url = "index.php?r=companies/companyinfo";

        $.ajax({
        url: url,
        dataType: 'json',
        method: 'GET',
        data: {text_in_search,left_items_cat},
        success: function (data, textStatus, jqXHR) {           
             // $( "#country"+id ).html(data[0].countries);
             console.log(data[0]);
           // **want to show this data in yii2 grid view**
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('An error occured!');
            alert('Error in ajax request');
        }
    });

控制台窗口

comapnies_matching
:
Array(3)
0
:
{name: "ADC Therapeutics Sarl", id: "402"}
1
:
{name: "ADC Therapeutics Sarl", id: "407"}
2
:
{name: "ADC Therapeutics Sarl", id: "412"}

如何在gridview中显示/填充此数据??

2 个答案:

答案 0 :(得分:1)

CompaniesController.php

public function actionCompanyinfo(){     

$text_in_search = $_GET['text_in_search'];
$left_items_cat = ltrim($_GET['left_items_cat']);

if($left_items_cat == "Companies"){

     $dataProvider= (new \yii\db\Query())
            ->select(['c.name', 'c.id'])
            ->from(['companies as c'])
            ->where('c.name LIKE :query') 
            ->addParams([':query'=>'%'.$text_in_search.'%'])
            ->all(); 

    return $this->renderPartial('gridview', [
        'dataProvider' => $dataProvider,
    ]); 

}}

您需要在gridview.php视图文件中呈现gridview

myjsfile.js

$("#getinfo").click(function(){
    var text_in_search = $("#companies-name").val();
    var left_items_cat = $('#left-items li.active').text();
    var url = "index.php?r=companies/companyinfo";

    $.ajax({
    url: url,
    method: 'GET',
    data: {text_in_search,left_items_cat},
    success: function (data, textStatus, jqXHR) {           
         //set the ajax response as your html content 
         $('#myDiv').html(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log('An error occured!');
        alert('Error in ajax request');
    }
});

答案 1 :(得分:0)

您可以从控制器渲染并返回Gridview的HTML,然后在获得响应时。将HTML代码放在要显示它的位置,可能包含当前Gridview的位置。

编辑,添加代码示例:

public function actionCompanyinfo(){
    $requestData = \Yii::$app->request->get();
    $text_in_search = isset($requestData['text_in_search']) ? $requestData['text_in_search'] : "";
    $left_items_cat = isset($requestData['left_items_cat']) ? trim($requestData['text_in_search']) : "";

    if($left_items_cat == "Companies"){
        $dataProvider = new ActiveDataProvider([
            'query' => (new \yii\db\Query())
            ->select(['c.name', 'c.id'])
            ->from(['companies as c'])
            ->where('c.name LIKE :query')
            ->addParams([':query'=>'%'.$text_in_search.'%']),
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        return \yii\grid\GridView::widget([
            'dataProvider' => $dataProvider,
            'columns' => [
                ['class' => 'yii\grid\SerialColumn'],
                // your columns here...
                ['class' => 'yii\grid\ActionColumn'],
            ],
        ]);
    }
}

在您的VIEW文件中,您应该创建一个区域(可能的元素 然后在您发出AJAX请求的js文件中,确保响应执行类似:

function (data, textStatus, jqXHR) {           
    $("#show-grid-here").html(data); //or data[0], I'm not sure. try both.
},