一、起因:
- 刚接触thymeleaf模版,网上找了一些文章,也没有对jQuery.load(url,data)的参数加以说明,现在记录下,具体的请查看代码。
二、需求 :
- 动态无刷新的渲染表格内容,说白了就是前台html页面load(发请求,可以带参数)一个代码片段(table.html),代码片段中的业务js自己写就可以了。
三、注意:
- 1在控制类中给代码片段table.html准备数据,用于渲染表格。
- 2主页面中的<div class="col-sm-8" th:fragment="table_refresh" id="table_refresh">
四、参考文档
thymeleaf-doc
layui-table
五、thymeleaf+layui渲染的主页面table效果如上图,代码如下
<div form-group> <label class="col-sm-3 control-label">已选题目:</label> <div class="col-sm-8" th:fragment="table_refresh" id="table_refresh"> <table class="table table-striped table-sm "> <thead> <tr> <th>#</th> <th>题目类型</th> <th>题干</th> <th>创建人</th> <th>创建时间</th> <th>备注信息</th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="ql:${questionList}"> <td th:text="${ql.questionId}"></td> <!--设置题目类型开始--> <td th:if="${ql.questionType =='single'}">单选题</td> <td th:if="${ql.questionType =='multi'}">多选题</td> <td th:if="${ql.questionType =='mix'}">混合题</td> <td th:if="${ql.questionType =='completion'}">简答题</td> <!--设置题目类型结束--> <td th:text="${ql.questionStem}"></td> <td th:text="${ql.createBy}"></td> <td th:text="${ql.remark}"></td> <td th:text="${#dates.format(ql.createTime, 'yyyy-MM-dd HH:mm:ss')}"></td> <td> <button type="button" class="btn btn-sm btn-primary create-logo">新增</button> <button type="button" class="btn btn-sm btn-danger del-logo" th:value="${ql.questionId}">删除 </button> </td> </tr> </tbody> </table> </div> </div>
六、发送请求获取页面(jQuery.load())
$('#table_refresh').load("/system/questionnaire/table",{Action:"post",metas:str});
参数说明:
- /system/questionnaire/table // 请求地址
- Action:"post" // 请求方式
- metas:str //此处str我放的是字符串,字符串id eg. 1, 2 , 3 , 5 , 12
七、controller代码:
@ApiOperation("为编辑页面表格准备数据") @PostMapping("/table") public String preparedDataForTable(String metas, ModelMap modelMap) { String[] metasArray = metas.split(","); List<String> questionIdList = Arrays.asList(metasArray); List<Question> questionList = new ArrayList<>(); questionIdList.forEach(item -> { questionList.add(questionService.getById(item)); }); modelMap.put("questionList", questionList);//为table.html准备数据 return prefix + "/table"; }
八、table.html代码如下,只是拿过来主页面的table
<table class="table table-striped table-sm "> <thead> <tr> <th>#</th> <th>题目类型</th> <th>题干</th> <th>创建人</th> <th>创建时间</th> <th>备注信息</th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="ql:${questionList}"> <td th:text="${ql.questionId}"></td> <!--设置题目类型开始--> <td th:if="${ql.questionType =='single'}">单选题</td> <td th:if="${ql.questionType =='multi'}">多选题</td> <td th:if="${ql.questionType =='mix'}">混合题</td> <td th:if="${ql.questionType =='completion'}">简答题</td> <!--设置题目类型结束--> <td th:text="${ql.questionStem}"></td> <td th:text="${ql.createBy}"></td> <td th:text="${ql.remark}"></td> <td th:text="${#dates.format(ql.createTime, 'yyyy-MM-dd HH:mm:ss')}"></td> <td> <button type="button" class="btn btn-sm btn-primary create-logo">新增</button> <button type="button" class="btn btn-sm btn-danger del-logo" th:value="${ql.questionId}">删除</button> </td> </tr> </tbody> </table>