这块代码应该很常用的,但是网上找找都找不到相似的内容。直接上代码:
生成JSON数据,发送到前端。
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/json;charset=UTF-8");
resp.setCharacterEncoding("UTF-8");
NewsService newsService = new NewsService();
//获取List对象
List<News> list = newsService.getNews();
//将List转换成json数据
Gson gson = new Gson();
String json = gson.toJson(list);
//发送json数据
resp.getWriter().print(json);
}
前端遍历JSON数据显示:
<script type="text/javascript">
window.onload = function() {
$.ajax({
url:'/news/getNews',
type:'GET',
data:{},
dataType:'json',
success:function(json){
$('#tb tr:gt(0)').remove();//删除之前的数据
var s = '';
for (var i = 0; i < json.length; i++) s += '<tr><td>' + json[i].id + '</td><td>' + json[i].title + '</td><td>' + json[i].createdate + '</td>'
+ '<td>' + json[i].userid +'<td>' + json[i].type + '<td><div class="table-fun"><a href="">修改</a><a href="">删除</a></div></td></tr>';
$('#tb').append(s);
}
});
}
</script>
<body>
<table class="public-cont-table" id="tb">
<tr>
<th style="width:15%">编号</th>
<th style="width:20%">标题</th>
<th style="width:15%">日期</th>
<th style="width:15%">用户</th>
<th style="width:15%">类型</th>
<th style="width:20%">操作</th>
</tr>
<tr>
<td>1</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<div class="table-fun">
<a href="">修改</a>
<a href="">删除</a>
</div>
</td>
</tr>
</table>
</body>
要是有用点赞关注。。。。