response将List对象转换成json对象并发送至前端以及前端如何遍历使用

这块代码应该很常用的,但是网上找找都找不到相似的内容。直接上代码:
生成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>

要是有用点赞关注。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值