六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 61|回复: 0

jQuery对后台json的解析

[复制链接]

升级  16.67%

19

主题

19

主题

19

主题

秀才

Rank: 2

积分
75
 楼主| 发表于 2013-1-29 11:50:00 | 显示全部楼层 |阅读模式
一个简单的例子,实现了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对象是导入的外部包。在附件中的源代码中有。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表