//Servlet的方式 package web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.UserService; public class SuggestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out=resp.getWriter(); String keyword=req.getParameter("keyword"); //利用service来进行测试 if(! "".equals(keyword.trim())){ UserService userService=new UserService(); String result=userService.queryUsernameByKeyword(keyword); if(result!=null){ out.println(result); }else{ out.println(""); } } out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
html页面内容:
<h3>利用Ajax实现搜索自动补齐提示!</h3> <div style="width:500px"> <input type="text" id="txtSearch" name="txtSearch"/> <input type="submit" id="cmdFind" name="cmdFind" value="搜索"/> <div id="suggest"></div> </div>
原生JS方式
var xhr; function createXhr(){ try{ return new XMLHttpRequest(); }catch(e){ return new ActiveXObject("Microsoft.XMLHTTP"); } } //用户名文本框失去焦点的处理函数; function findSuggest(){ xhr=createXhr(); var keyword=document.getElementById("txtSearch").value; alert(keyword); xhr.onreadystatechange=callback; xhr.open("post","suggestAction",true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send("keyword="+keyword); } function callback(){ if(xhr.readyState==4){ if(xhr.status==200){ var sobj=document.getElementById("suggest"); sobj.innerHTML=""; var str=xhr.responseText.split(","); var suggest=""; if(str.length>0 && str[0].length>0){ for(i=0;i<str.length;i++){ suggest+="<div onclick='setSearch(this.innerHTML);'"; suggest+=">"+str[i]+"</div>"; } sobj.innerHTML=suggest; document.getElementById("suggest").style.display="block"; }else{ document.getElementById("suggest").style.display="none"; } } } } function setSearch(obj){ document.getElementById("txtSearch").value=obj; document.getElementById("suggest").style.display="none"; }
2.使用jquery的方式
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script> <script type="text/javascript"> //1.找对象;2.定事件;匿名事件; $(function(){ $("#txtSearch").keyup(function(){ //发送post请求,设置请求url,请求数据,成功返回函数; $.post("suggestAction",{keyword:$("#txtSearch").val()},callback); }); }); function callback(data){ var sobj=$("#suggest"); sobj.innerHTML=""; var suggest=""; var str=data.split(",");alert(data); if(str.length>0 && str[0].length>0){ for(i=0;i<str.length;i++){ suggest+="<div onclick='setSearch(this.innerHTML);'"; suggest+=">"+str[i]+"</div>"; } sobj.html(suggest).css("display","block"); }else{ sobj.css("display","none"); } } //将内容填充到搜索框中; function setSearch(obj){ $("#txtSearch").val(obj); $("#suggest").css("display","none"); } </script>