Yii2:如何将JSON加载到GridView中?

时间:2017-09-13 17:17:39

标签: javascript php jquery json yii2

我有一个名为response的JSON对象,它是来自服务器的响应。它在这里制作:

<?php
$this->registerJs(<<<JS
    $(function($) {
        function reloadGridView(idColor) {
            $.ajax({
                url: "/colors?idcolor=" + idColor,
                dataType: 'json',
                success: function(res) {
                    console.log(JSON.stringify(response, null, 4));
                    $.pjax.reload({container: "#gridColors"});
                }
            });
        }

        $('#myCkeckbox).on('click', function(e) {
            var idColor = $('#idPerson').val();
            reloadGridView(idPerson);

        });
    });
JS
);
?>

这是response对象:

[
    {
        "number": 1,
        "name": "Orange"
    },
    {
        "number": 2,
        "name": "White"
    },
]

我希望使用 jQuery 在下一个GridView中展示它,但我不知道该怎么做,因为respose JavaScript < / strong>和GridView PHP

<?
Pjax::begin(['id' => 'gridColors']);
echo GridView::widget([
    'summary' => '',
    'dataProvider' => $dataProvider,
    'columns' => [
        'number',
        'name'
    ],
]);
Pjax::end();
?>

1 个答案:

答案 0 :(得分:1)

尝试这样的事情......

use yii\helper\Json;
use yii\data\ArrayDataProvider;

$dataProvider = new ArrayDataProvider([
    // Define data array by decoding json-string in $jsonResponseString
    // Converted from your Json object somehow...
    'allModels' => Json::decode($jsonResponseString),
    // Might need this too... (assuming number is unique identifier)
    'key' => 'number',
    // Setup sorting if not using default
    'sort' => [
        'attributes' => ['number', 'name'],
    ],
    // Set pagination if not using default
    'pagination' => [
        'pageSize' => 10,
    ],
]);

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'number',
        'name',
    ],
]);

此代码未经过测试,但希望能提供一些帮助。