jQuery对后台json的解析

一个简单的例子,实现了jQuery对后台的json数据进行解析。

页面由jQuery发送一个Ajax请求,后台的servlet通过使用json的组件构造成json数据返回页面。页面进行解析显示。

前端代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<title>json数据练习</title>
</head>
<body>
<center>
	<strong>页面使用jQuery库发生Ajax请求,将服务器端返回的json数据显示出来</strong><br>
	<span>以下是服务器端返回的json数据</span>
	<hr>
	<table id="tab" border="1">
		<tr>
			<td>名称</td>
			<td>地址</td>
			<td>Email</td>
		</tr>
	</table>
</center>
	<script type="text/javascript">
		jQuery(document).ready(function(){
			jQuery("#tab").hide();
			jQuery.post(
				"jsonServlet",
				function(json){
					for(var i = 0; i < json.test.length;i++){
						jQuery("#tab").append("<tr><td>"+json.test[i].name+"</td><td>"+json.test[i].address+"</td><td>"+json.test[i].email+"</td></tr>");
					}
					jQuery("#tab").show();
				},
				"json"
			);
		});
	</script>
</body>
</html>

 后台处理代码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		List<UserBean> users = new ArrayList<UserBean>();
		UserBean userBean1 = new UserBean();
		userBean1.setName("张三");
		userBean1.setAddress("陕西西安");
		userBean1.setEmail("zhangsan@163.com");
		users.add(userBean1);
		
		UserBean userBean2 = new UserBean();
		userBean2.setName("李四");
		userBean2.setAddress("山西太原");
		userBean2.setEmail("lis@163.com");
		users.add(userBean2);
		
		UserBean userBean3 = new UserBean();
		userBean3.setName("王五");
		userBean3.setAddress("甘肃兰州");
		userBean3.setEmail("wangwu@163.com");
		users.add(userBean3);
		
		JSONObject jsonObj = new JSONObject();
		try {
			jsonObj.put("test", users);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		String jsonStr = jsonObj.toString();
		out.print(jsonStr);
	}

 

再有就是一个JavaBean,就不展示了,后台代码中用到的JSONObject对象是导入的外部包。在附件中的源代码中有。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值