本次实例是通过ajax请求后端数据,然后后端将数据返回给前端,需要一个GSON插件(下载地址:https://mvnrepository.com/artifact/com.google.code.gson/gson):
前端代码:
<button id="select">查找类型</button>
<table border="1">
<thead>
<td>id</td>
<td>名称</td>
<td>简述内容</td>
</thead>
<tbody id="tb"></tbody>
</table>
后端代码:
@RequestMapping(value = "/test",produces = "text/plain;charset=utf-8"/*防止数据到前端乱码*/)
@ResponseBody
public String test(Model model){
List<Type> list = typeManagerService.selectType();
model.addAttribute("lists",list);
Gson gson = new Gson();
//此处是将list集合转换为json对象
String att = gson.toJson(list);
return att;
}
第一种方式(for循环):
<script type="text/javascript">
$("#select").click(function () {
$.ajax({
url:'/test',
type:'get',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
dataType:'json',
success:function (data) {
$("#tb").empty();
var htm = "";
for (var i = 0;i<data.length;i++){
htm+="<tr><td>"+data[i].type_id+"</td><td>"+data[i].type_name+"</td><td>"+data[i].type_describe+"</td></tr>";
}
$("#tb").append(htm);
}
})
})
</script>
第二中方式:$.each():
$.each(selector,function(index,object)):
- selector代表含有json对象的值
- index代表下标数字从0开始
- object代表当前对象
<script type="text/javascript">
$("#select").click(function () {
$.ajax({
url:'/test',
type:'get',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
dataType:'json',
success:function (data) {
$("#tb").empty();
var htm = "";
$.each(data,function (index,obj) {
htm+="<tr><td>"+obj.type_id+"</td><td>"+obj.type_name+"</td><td>"+obj.type_describe+"</td></tr>";
})
$("#tb").append(htm);
}
})
})
</script>