今天第一次使用layui的数据表格,刚开始根本出不来数据,然后问了一下我室友(因为我室友前几天使用过并且也成功了),发现他是直接使用的layui数据表格自带的**“url”**
属性实现的数据绑定,然后自己也试了一下这个绑定方法,发现数据还是出不来
然后想着换一个思路,就将整个数据表格定义为方法
//通过定义为方法将参数(数据)传递给表格,并为表格动态添加数据
function UserTable(list) {
layui.use('table', function () {
var table = layui.table;
table.render({
elem: '#test'
//使用layui数据表格的data属性将Ajax调用的后台数据绑定
, data: list
, toolbar: '#toolbarDemo'
, title: '员工信息表'
, cols: [[
//fixed此格式会固定表格栏并处于最上级,但不能使用这个直接绑定数据这个只单纯的用于固定列
//fixed: 'left'固定列在最左侧
// field这里时绑定自己放回数据中的字段
//sort: true 定义是否调用layu表格的正序逆序排序
{ field: 'UserID', title: 'ID', width: 50, fixed: 'left', sort: true }
, { field: 'UserName', title: '姓名', fixed: 'left', width: 80, }
, { field: 'UserNumber', title: '工号', fixed: 'left', width: 120, sort: true }
, { field: 'NationalName', title: '民族', width: 60 }
, {
field: 'UserBirthday', title: '生日', width: 120
//templet----layui数据表格绑定数据时可以使用该属性进行修饰(正常的写js方法就好)
, templet: function (d) {
//调用时间格式转换方法将json数据格式的时间转换为电脑常见的时间格式
//return返回的就是最后你要的数据
return getFDate(d.UserBirthday);
}
}
, {
field: 'UserSex', title: '性别', width: 60
, templet: function (d) {
//使用三目运算符转换识别的0/1为男女
return d.UserSex == 0 ? "男" : "女";
}
}
, { field: 'SchoolRecordName', title: '学历', width: 60 }
, { field: 'UserPwd', title: '登录密码', edit: 'text', width: 100 }
, { field: 'UserPhone', title: '手机', width: 130, edit: 'text' }
, { field: 'UserEmail', title: '邮箱', width: 190, edit: 'text' }
, { field: 'UserUid', title: '身份证', width: 180 }
, { field: 'UserPhoto', title: '照片', width: 80, edit: 'text' }
, { field: 'BankName', title: '银行', width: 180 }
, { field: 'UserBankCard', title: '工资卡', width: 200 }
, { field: 'UserAddress', title: '住址', width: 150 }
, { field: 'DepartmentName', title: '部门', width: 80 }
, { field: 'PositionName', title: '职务', width: 120 }
//在表格最后添加一个固定的操作列
, { fixed: 'right', title: '操作', toolbar: '#barDemo', width: 120 }
]]
, id: 'testReload'
, page: true分页
}
});
然后通过Ajax调用后台数据并将数据传给数据表格
$.ajax({
url: "/MessageSetting/UserTableAjax",
type: "post",
dataType: "json",
data: {},
success: function (list) {
if (list != null) {
//传递参数给数据表格方法
UserTable(list);
}
},
error: function (data) {
console.info(data);
}
});
这里一定要注意因为时通过ajax返回的json格式数据所以你的时间格式会变为类似这种/Date(2367828670431)格式的json时间数据
这里的时间格式是转换成:2016-07-11这一种年月日的格式
//Json格式时间转换
function getFDate(date) {
var d = eval('new ' + date.substr(1, date.length - 2));
var ar_date = [d.getFullYear(), d.getMonth() + 1, d.getDate()];
for (var i = 0; i < ar_date.length; i++) ar_date[i] = dFormat(ar_date[i]);
return ar_date.join('-');
}
function dFormat(i) {
return i < 10 ? "0" + i.toString() : i;
}