上一篇提到了后台返回的json格式,此文主要说下如何解析返回的对象:
如果json返回的格式为:
{"id":0,"name":"delvelop group ","users":[{"gender":"female","id":2,"mobile":"13645445544","name":"july"},{"gender":"male","id":3,"mobile":"15915632158","name":"cayden"}]}
那么Html或Jsp解析如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <Meta http-equiv="pragma" content="no-cache"> <Meta http-equiv="cache-control" content="no-cache"> <Meta http-equiv="expires" content="0"> <Meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <Meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(function(){ $('#mybtn').click(function(){ $.get("http://localhost:8090/Test/servlet/first",function(data){ $('#result').text(data);//直接展示JSON数据 var j = eval("("+data+")"); $('#groupId').text( j.name); var res = "<ul>"; $.each(j.users,function(i,n){ res += "<li>" + n["name"] +"</li>"; res += "<li>" + n["mobile"] +"</li>"; var gender = n["gender"]; if(gender == "male") gender = "男"; else gender = "女"; res += "<li>" + gender +"</li>"; }); res += "</ul>"; $('#result').append(res); }); return false; }); }); </script> </head> <body> <input type="button" id="mybtn" value="展示数据"> <ul id="groupId"></ul> <div id="result"> </div> </body> </html>
源码下载地址为: http://dl.dbank.com/c0tjoj29j6
如有疑问,欢迎留言咨询,谢谢。
原文链接:https://www.f2er.com/json/290649.html