Conditions: jquery-1.6.2.js 及相关JSON Jar包
1:定义一个TestCollServlet类:
response.setCharacterEncoding("UTF-8"); User user1 = new User(1,"忘不",22); User user2 = new User(2,"李四",22); User user3 = new User(3,"王五",22); User user4 = new User(4,"赵六",22); List<User> list = new ArrayList<User>(); list.add(user1); list.add(user2); list.add(user3); list.add(user4); JSONArray array=JSONArray.fromObject(list); System.out.println(array.toString()); response.getWriter().write(array.toString());
2:JSP页面:
<script type="text/javascript" src="js/jquery-1.6.2.js"></script> <script type="text/javascript"> function findUser(){ $.get("TestCollServlet",function(data){ alert(data); var list=jQuery.parseJSON(data); for(var i=0;i<list.length;i++){ var user=list[i]; var tr=$("<tr>"); tr .append($("<td>").text(user.name)) .append($("<td>").text(user.age)) .appendTo($("#list")); } }); } </script> </head> <body> <table border="1" width="80%" align="center"> <tr><th>姓名</th> <th>年龄</th> </tr> <tbody id="list"> </tbody> </table> <input type="button" value="取得信息" onclick="findUser()" /> </body> </html>原文链接:https://www.f2er.com/ajax/165193.html