ajax实现通过empno不刷新网页查询emp数据表对象(使用JSON)
JSP
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <%@include file="commons/basePath.jsp" %> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>查员工</title> <script type="text/javascript" src="js/createXHR.js"></script> <script type="text/javascript"> function find(){ var empno = document.getElementById("empno").value.trim(); createXHR(); xhr.open("POST","findEmp"); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ var date = xhr.responseText; var obj = JSON.parse(date); document.getElementById("ename").value=obj.ename; document.getElementById("job").value=obj.job; document.getElementById("sal").value=obj.sal; document.getElementById("hiredate").value=obj.hiredate; document.getElementById("dept").value=obj.deptno; } } xhr.send("empno="+empno); } </script> </head> <body> <p>员工编号:<input id="empno"> <input type="button" value="查询" onclick="find()"> </p> <hr> <div> <p>姓名<input id="ename"></p> <p>职位<input id="job"></p> <p>薪水<input id="sal"></p> <p>雇佣日期<input type="date" id="hiredate"></p> <p> 部门名<select id="dept"> <option value="10">ACCOUNTING</option> <option value="20">RESEARCH</option> <option value="30">CHICAGO</option> </select> </p> </div> </body> </html>
servlet(QueryTableDAO这个不用在意,这是我通过反射写的单表查询万能dao,就当他是个普通的dao方法就可以了)
package top.yibobo.web.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; 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 net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import net.sf.json.JsonConfig; import top.yibobo.pojo.Emp; import top.yibobo.util.DateValueProcessor; import top.yibobo.util.QueryTableDAO; @WebServlet("/findEmp") public class EmpServlet extends HttpServlet{ QueryTableDAO empdao = new QueryTableDAO("emp_pyb", Emp.class); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); String empno = req.getParameter("empno"); System.out.println(empno); Emp e = empdao.findSingle("empno", empno); JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(Date.class, new DateValueProcessor()); JSONObject jo = (JSONObject) JSONSerializer.toJSON(e,config); PrintWriter out = resp.getWriter(); out.println(jo); out.close(); } }