如何在yii2 gridview中显示json数据

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

标签: json yii2

我想在gridview中显示json数据。我在控制台窗口中获取数据。我想在gridview.how中显示这样做。下面给出了代码

在控制器中

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
    ]);  

    }
}

在视图中

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

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

在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');
        }
    });

的console.log

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"}

在控制台窗口中,我得到了所需的输出,但我希望它在网格视图中显示该数组..怎么做?

1 个答案:

答案 0 :(得分:0)

您可以通过使用框架的Pjax小部件来实现此目的。

在您看来:(如果您不使用模型,请不要使用ActiveForm)

<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;

//Get active filters from request GET
$get = Yii::$app->request->get();
$name = isset($get['name']) ? $get['name'] : '';
$left_items_cat = isset($get['left_items_cat']) ? $get['left_items_cat'] : '';
?>

<?php Pjax::begin(); ?>
<?= Html::beginForm(['companies/companyinfo'], 'get', ['data-pjax' => '',]); ?>
<?= Html::dropDownList('left_items_cat', $left_items_cat,
    ['' => '', 'Companies' => 'Companies', 'Other' => 'Other'], ['class' => 'form-control']) ?>
<?= Html::input('text', 'name', $name, ['class' => 'form-control']) ?>
<?= Html::submitButton('Get Info', ['class' => 'btn btn-success', 'name' => 'getInfo']) ?>
<?= Html::endForm() ?>
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        'name',
    ],
]); ?>
<?php Pjax::end(); ?>

在你的控制器中:

public function actionCompanyinfo()
{
    // Init DataProvider empty
    $dataProvider = new ArrayDataProvider(['allModels' => []]);
    // Manage the params send in request GET
    $text_in_search = $_GET['name'];
    $left_items_cat = ltrim($_GET['left_items_cat']);

    if ($left_items_cat == "Companies") {
        // Query rows and populate DataProvider
        $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();

        $dataProvider->allModels = $query;
    }

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