有时我们需要做一个gird,但gird的列名确是变化的,我们需要从数据库中先查出列名,也就是说我们要实现一个动态的gird.
下面的代码是我实现动态gird的方法,简单但强大,数据是读的json文件,实际使用的时候可以把在后台把数据存在map中再转成json格式的字符串即可,json格式要符合我给出的格式。
首先是json数据:
{
"data": [
{
"number": "1",
"field1": "a",
"field2": "b",
"field3": "c"
},
{
"number": "2",
"field1": "d",
"field2": "e",
"field3": "f"
},
{
"number": "3",
"field1": "g",
"field2": "h",
"field3": "i"
}
],
"columnModle": [
{
"text": "序号",
"dataIndex": "number",
"width": 40,
"locked":true
},
{
"text": "字段1",
"dataIndex": "field1"
},
{
"text": "字段2",
"dataIndex": "field2"
},
{
"text": "字段3",
"dataIndex": "field3"
}
],
"fieldsNames": [
{
"name": "number"
},
{
"name": "field1"
},
{
"name": "field2"
},
{
"name": "field3"
}
]
}
Ext.onReady(function() {
Ext.Ajax.request({
url : "page/data/test1.json",
params : {
},
success : function(response, config) {
json = Ext.util.JSON.decode(response.responseText);
var store = new Ext.data.JsonStore({
data : json.data,
fields : json.fieldsNames
});
var column_ = json.columnModle;
var grid = new Ext.grid.Panel({
title : '动态表格',
region : 'center',
xtype: 'locking-grid', //类型为锁定表格
split : true,
renderTo : Ext.getBody(),
height : 300,
width : 1200,
columns: column_,
store:store
});
},
failure : function() {
}
});
});
奉上截图: