EasyUI Datagrid 渲染请求返回的数据有多种方式,以下为你详细介绍:
#### 远程加载数据
可通过设置 `url` 属性来实现远程加载数据。示例代码如下:
```javascript
$('#dg').datagrid({
width: 800,
scrollbarSize: 0,
fitColumns: true,
url: 'http://www.cpcandcj.com/querycpc',
columns: [[
{ field: 'id', title: '主键', width: '100' },
{ field: 'name', title: '教练姓名', width: '100' },
{ field: 'age', title: '年龄', width: '100' },
{ field: 'birthday', title: '出生日期', width: '100' },
{ field: 'expertin', title: '专业擅长', width: '200' }
]],
loadMsg: '数据加载,请稍等.....',
loadFilter: function (data) {
for (var i = 0; i < data.length; i++) {
data[i]['expertin'] = returntext('coach_expert', data[i]['expertin']);
}
return data;
}
});
```
在上述代码中,`url` 指定了远程数据的请求地址,`loadFilter` 函数可对返回的数据进行预处理,处理完成后返回处理后的数据供 Datagrid 渲染 [^2]。
#### 本地数据渲染
如果数据是本地的,可以直接在初始化 Datagrid 时传入数据:
```javascript
$(function () {
var data = [
{ itemid: 'ITEM001', productname: 'Product 1', listprice: 100, unitcost: 80, attr1: 'Attribute 1', status: 'Active' },
{ itemid: 'ITEM002', productname: 'Product 2', listprice: 200, unitcost: 150, attr1: 'Attribute 2', status: 'Inactive' }
];
$('#dg').datagrid({
data: data,
columns: [[
{ field: 'itemid', title: 'Item ID', width: 100 },
{ field: 'productname', title: 'Product Name', width: 150 },
{ field: 'listprice', title: 'List Price', width: 100, align: 'right' },
{ field: 'unitcost', title: 'Unit Cost', width: 100, align: 'right' },
{ field: 'attr1', title: 'Attribute', width: 250 },
{ field: 'status', title: 'Status', width: 70, align: 'center' }
]]
});
});
```
#### 动态加载数据
可以使用 `load` 方法动态加载数据:
```javascript
$('#dg').datagrid('load', {
param1: 'value1',
param2: 'value2'
});
```
使用 `load` 方法时,传入的参数会代替默认查询参数,且会跳到第一页然后刷新数据。若要刷新当前页数据,可使用 `reload` 方法 [^1]。
#### 数据处理
可通过 `formatter` 函数自定义列的渲染方式:
```javascript
$('#dg').datagrid({
url: 'data.json',
columns: [[
{
field: 'status',
title: 'Status',
width: 70,
align: 'center',
formatter: function (value, row, index) {
if (value == 'Active') {
return '<span style="color:green">Active</span>';
} else {
return '<span style="color:red">Inactive</span>';
}
}
}
]]
});
```
上述代码中,`formatter` 函数会根据 `status` 字段的值,将其渲染为不同颜色的文本 [^1]。