EasyUI学习-----DataGrid动态创建列

1.JSON本地文件

{
    "total": 2,
    "rows": [
        {
            "code": 1001,
            "name": "苹果",
            "price": 8.00
        },
        {
            "code": 1002,
            "name": "葡萄",
            "price": 10.00
        }
    ]
}

2.动态创建列

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>动态生成列</title>
        <link rel="stylesheet" type="text/css" href="jquery-easyui-1.5.1/themes/default/easyui.css">
        <link rel="stylesheet" type="text/css" href="jquery-easyui-1.5.1/themes/icon.css">
        <script type="text/javascript" src="jquery-easyui-1.5.1/jquery.min.js"></script>
        <script type="text/javascript" src="jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
        <script type="text/javascript" src="jquery-easyui-1.5.1/locale/easyui-lang-zh_CN.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#dg').datagrid({
                    title: '商品信息',
                    fitColumns: true,
                });

                $.ajax({
                    type: 'get',
                    url: 'datagridData.json',
                    dataType: 'json',
                    success: function(data) {
                        console.log(JSON.stringify(data.rows))
                        var totalData = data.rows;
                        var cols = [];
                        //获取属性名称
                        for(var st in totalData[0]) {
                            //动态生成列        
                            cols.push({
                                "field": st,
                                "title": st,
                                "width": 100,
                                align: "center"
                            });
                        }
                                        
                        $("#dg").datagrid({
                            columns: [cols]
                        }).datagrid('loadData', data.rows);
                    }
                })
            })
        </script>
    </head>

    <body>
        <table id="dg" style=" 500px;height: 300px;"></table>
    </body>

</html>
原文地址:https://www.cnblogs.com/fengfuwanliu/p/11139453.html