标签:return 数据库 inf 数据 bin ons rip 分享图片 成功
out.print("服务器返回的内容: \n");" ,然后找了大半天的bug! 毕竟,加上后,json就没法进行解析了!!
public class Users { private int id; private String password,username; // getter/setter........ }
import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList;
@WebServlet("/demo") public class DemoServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("执行demo控制器............"); Users users=new Users(); //建立pojo对象 users.setId(1); users.setPassword("123456"); users.setUsername("张三"); Users users2=new Users(); //建立pojo对象2 users2.setId(2); users2.setPassword("123456"); users2.setUsername("李四"); ArrayList<Users> list=new ArrayList(); list.add(users); list.add(users2); ObjectMapper mapper = new ObjectMapper(); //将对象list转化为json字符串 String result= mapper.writeValueAsString(list); //请求头:MIME 格式; resp.setContentType("application/json;charset=utf-8"); //设置json字符流为utf-8 PrintWriter out = resp.getWriter(); // out.print("服务器返回的内容: \n"); out.println(result); out.flush(); out.close(); } }
测试/demo 控制器
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> <script type="text/javascript" src="js/jquery-1.7.2.js"></script> <script type="text/javascript"> $(function () { $("a").click(function () { $.post("demo",{},function (data) { var result=""; for(var i=0;i<data.length;i++){ result+="<tr>"; result+="<td>"+data[i].id+"</td>"; result+="<td>"+data[i].username+"</td>"; result+="<td>"+data[i].password+"</td>"; result+="</tr>"; } //$("table").append(result); //相当innerHTML先清空后添加 $("#mytbody").html(result); }) return false; }) }); </script> </head> <body> <a href="demo">点击显示下面表单的详细信息</a> <br/> <br> <table border="1"> <tr> <td>编号</td> <td>账号</td> <td>密码</td> </tr> <tbody id="mytbody"></tbody> </table> </body> </html>
Ajax -02 -JQuery+Servlet -实现页面点击刷出表格数据
标签:return 数据库 inf 数据 bin ons rip 分享图片 成功
原文地址:https://www.cnblogs.com/zhazhaacmer/p/10315380.html