起初我给layui表格的数据接口绑定的是一个json文件,但是这是静态的,如果在运行中创建json文件,表格会找不到相应的json文件。
于是在controller中创建相应该url的方法,返回json数据的方法,从而动态的显示表格信息。
layui数据接口的格式要求:
{
"code": 0,
"msg": "",
"count": 1000,
"data": [{}, {}]
}
HTML中的片段代码:
<script type="text/javascript" src="/layui/layui.js"></script>
<script>
layui.use('table', function(){
var table = layui.table;
//第一个实例
table.render({
elem: '#demo'
,height: 600
,url: '/paper_info' //数据接口
,page: true //开启分页
,title: '教师信息'
,cols: [[ //表头
{field: '_id', title: 'ID', width:220, sort: true,event: 'clos'}
,{field: 'index', title: '所属教师', width:100, event: 'clos'}
,{field: 'title', title: '标题', width:250, event: 'clos'}
,{field: 'authors', title: '作者列表', width:200, event:'clos'}
,{field: 'source', title: '论文来源', width: 200, event: 'clos'}
,{field: 'times', title: '时间', width: 130, sort: true, event:'cols'}
,{field: 'database', title: '论文种类', width: 120, sort: true, event: 'clos'}
,{field: 'counted', title: '引用次数', width: 100, sort: true, event: 'clos'}
,{field: 'toolbar', title: '工具栏', width: 170, toolbar: '#barDemo'}
]]
});
});
});
</script>
在Controller中配置该url:
@ResponseBody
@RequestMapping("/paper_info")
public String paperInfo() throws IOException{
Convert2json convert2json = new Convert2json(mongoTemplate); //该方法是我项目中可以返回json的Method
return convert2json.saveAsJson();
}
问题来了如果想要带参数的url该怎么办?
HTML代码
<script src="/layui/layui.js"></script>
<script>
layui.use('table', function(){
var table = layui.table;
var author = window.location.href.split("=")[1]
//第一个实例
table.render({
elem: '#demo'
,height: 600
,url: '/paperList?author='+author //数据接口
,page: true //开启分页
,title: '教师信息'
,cols: [[ //表头
{field: '_id', title: 'ID', width:220, sort: true,event: 'clos'}
,{field: 'index', title: '所属教师', width:100, event: 'clos'}
,{field: 'title', title: '标题', width:250, event: 'clos'}
,{field: 'authors', title: '作者列表', width:200, event:'clos'}
,{field: 'source', title: '论文来源', width: 200, event: 'clos'}
,{field: 'times', title: '时间', width: 130, sort: true, event:'cols'}
,{field: 'database', title: '论文种类', width: 120, sort: true, event: 'clos'}
,{field: 'counted', title: '引用次数', width: 100, sort: true, event: 'clos'}
,{field: 'toolbar', title: '工具栏', width: 170, toolbar: '#barDemo'}
]]
});
</script>
** 我们在url中添加了参数author ,可以在controller中对该参数进行解析:**
@ResponseBody //可以利用@RequestParam标记来解析url中的参数
@RequestMapping("/paperList")
public String paperList(@RequestParam("author") String name) throws IOException {
AuthorPaper2json authorPaper2json = new AuthorPaper2json(mongoTemplate);
return authorPaper2json.saveAsJson(name);
}
如果不太会构建相应的json数据,尤其是mongoDB的数据可以看我以往写过的文章:
https://blog.csdn.net/qq_36801317/article/details/107408397
希望大家批评指正~