1.背景
事情是这样的。ftl页面里有一个动态的表格,表格里面的数据是用ftl表达式遍历一个list得到的数据,类似这样:
...
<tbody>
<#list peopleList as people>
<tr>
<td>${people.id}</td>
<td>${people.address}</td>
<td>${people.name}</td>
</tr>
</#list>
</tbody>
...
2.需求
现在需求是,点击保存按钮时将表格里面的数据传到后台,存入数据库中。
3.前端代码
我们在JavaScript代码中嵌套ftl表达式,通过ajax将数据传到后台,请求后台方法。
$(document).on("click", '#Button_Save', function () {
var peopleList = new Array();//声明一个数组
var peopleListSize = "${peopleList?size}";
if(peopleListSize != 0){
var j = 0;
<#list peopleList as people>
j++;
var people= ${people};
peopleList.push(people);
</#list>
}
$.ajax({
type: "POST",
url: contextPath + "/operation/add/",
data: {"peopleList":JSON.stringify(peopleList)},
dataType: "json",
success: function (data) {
if (data.resultCode == 0) {
//成功
alert("保存成功");
} else {
//错误
alert(data.resultData);
}
},
error: function (data) {
$("#operationButtonList").show();
alert("请求失败!");
}
});
});
4.后端代码
后台代码就是接收这个list并将其存到数据库,有一点注意的是,我们在向后台传数据的时候,不能够直接传这个list,在这里我用了一个JSON.stringify()函数,在后台我们直接用String类型参数来接收。
@PostMapping("/add")
@ResponseBody
public JSONObject updatePeopleInfo(@RequestParam String peopleList, HttpServletRequest request) {
List<People> peopleList = new ArrayList<People>();
peopleList= JSON.parseArray(peopleList, People.class);
for(People people: peopleList){
People peopleInfo= new People();
peopleInfo.setId(people.getId());
peopleInfo.setAddress(people.getAddress());
peopleInfo.setName(people.getName());
peopleMapper.updateByPrimaryKeySelective(peopleInfo);
}
logger.info("peopleInfo:{}", peopleInfo);
JSONObject result = ResponseUtil.packSuccessResult("保存成功");
return result;
}