ajax2.jsp:<!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"><title>Insert title here</title><script type="text/javascript></script><script type="text/javascript"> function showEmps(){ new Ajax.Request( "empserv?t="+new Date().getTime(), { method:"post", parameters:{"name":$F("name")}, onSuccess:function(req){ var emps = req.responseText.evalJSON(); //清空table表格 clearTable(); //循环生成table列表 for(i=0;i<emps.length;i++){ var emp = emps[i]; //在table最后位置添加一行tr var tr = $("tb").insertRow($("tb").rows.length); tr.onmouseover = function(){ this.style.backgroundColor = "#00FFFF"; } tr.onmouseout = function(){ this.style.backgroundColor = "#FFFFFF"; } //添加td,显示name var name_td = tr.insertCell(tr.cells.length); name_td.innerHTML = emp.name; name_td.onclick = function(){ $("name").value = this.innerHTML; //清空table表格 clearTable(); } //添加td,显示salary var sal_td = tr.insertCell(tr.cells.length); sal_td.innerHTML = emp.salary; } } } );}function clearTable(){ var len = $("tb").rows.length; for(i=len-1;i>=0;i--){ $("tb").deleteRow(i); }}</script></head><body><input type="text" name="name" id="name" oninput="showEmps()" onkeyup="showEmps()"/><input type="button" value="清空" onclick="clearTable()"/><input type="button" value="查询" onclick="showEmps()"/><hr><table id="tb"></table></body></html>EmpServlet :package serv;import java.io.IOException;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.sql.SQLException;import java.util.List;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import dao.EmployeeDAO;public class EmpServlet extends HttpServlet{ public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException{ doGet(request,response); } public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{ request.setCharacterEncoding("utf-8"); String name = request.getParameter("name"); System.out.println(name); response.setContentType("text/json;charset=utf-8"); EmployeeDAO empDAO = new EmployeeDAO(); try { List list = empDAO.findLikeName(name); JSONArray json = JSONArray.fromObject(list); String emps = json.toString(); System.out.println(emps); PrintWriter out = response.getWriter(); out.print(emps); out.close(); } catch (Exception e) { e.printStackTrace(); } }}
查询谷 - www.chaxungu.com
ajax示范2
编辑:chaxungu时间:2022-10-10 23:24:01分类:web开发
ajax示例2