ajax升级版值百度搜索

tech2022-07-14  180

做一个模糊查询 做百度关键字查询 先做一个js的文件 然后在jsp页面调用它

var req; function ajaxSend(url,fun){ //ajax 的核心对象 是 XMLHttpRequest req=new XMLHttpRequest(); //设置回调函数名称 req.onreadystatechange=function(){ if(req.readyState==4&&req.status==200){ //通过回调 获得服务器返回的值 var str=req.responseText; fun(str); //document.getElementById("h").innerHTML=str; } }; //设置提交地址 req.open("get", url); //提交 req.send(); }

jsp页面的话

<script src="ajax.js"></script> <script > function baidu(obj){ document.getElementById("h").style.display="block"; document.getElementById("h").innerHTML=""; if(obj!=""||obj!=null){ ajaxsend("baiduserlet?name="+obj,function(str){ document.getElementById("h").innerHTML=str; }); } } function ok(obj){ document.getElementById("k1").value=obj.innerHTML; document.getElementById("h").style.display="none"; } </script> <body> <input onkeyup="baidu(this.value)" id="k1"/> <div id = "h"></div> </body>

逻辑层

try { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); EmpDAO dao = new EmpDAO(); // System.out.println(name); List<String> list = dao.mohu(name); //调用回调函数 传入的集合里面的一个个的值 list.forEach(x->out.println("<div οnclick=\"ok(this)\" οnmοuseοver=\"this.style.backgroundColor='#777777'\" οnmοuseοut=\"this.style.backgroundColor='#FFFFFF'\"> "+x+"</div>")); out.flush(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }

用了连接数据库 查询名字 在都查询出来

public List<String> mohu(String ename) throws Exception{ List<String> list = new ArrayList<String>(); Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement("select ename from emp where " + " ename like ?"); ps.setString(1,"%"+ename+"%"); ResultSet rs = ps.executeQuery(); while(rs.next()) { list.add(rs.getString(1)); } this.closeAll(rs, ps, conn); return list; }
最新回复(0)