jQuery文本框输入自动提示,类似百度搜索效果
使用简介
一、创建文本框,其id为query
<input type="text" name="q" id="query" />
<script type="text/javascript" src="<%=basePath%>js/jquery-1.4.2.min.js"></script><script type="text/javascript" src="<%=basePath%>js/jquery.autocomplete.js"></script>
<link href="<%=basePath%>css/css.css" rel="stylesheet" type="text/css" />
.autocomplete-w1 { background:url(img/shadow.png) no-repeat bottom right; position:absolute; top:0px; left:0px; margin:6px 0 0 6px; /* IE6 fix: */ _background:none; _margin:1px 0 0 0; }.autocomplete { border:1px solid #999; background:#FFF; cursor:default; text-align:left; max-height:350px; overflow:auto; margin:-6px 6px 6px -6px; /* IE6 specific: */ _height:350px; _margin:0; _overflow-x:hidden; }.autocomplete .selected { background:#F0F0F0; }.autocomplete div { padding:2px 5px; white-space:nowrap; overflow:hidden; }.autocomplete strong { font-weight:normal; color:#3399FF; }
package servlet;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;public class JqueryAuto extends HttpServlet {private static final long serialVersionUID = -3735305758332148214L;public JqueryAuto() {}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();/* * 返回数据格式必须是json数据,如下所示,本次重点不是json,不做json转换,使用土办法实现 * { query:'Li', suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'], data:['LR','LY','LI','LT'] } * */String keyWord = request.getParameter("query");//获取的属性必须是“query”,这是jquery插件规定的System.out.println("关键是:"+keyWord);StringBuilder sb = new StringBuilder();sb.append("{");sb.append("query:'"+keyWord+"',");/*下面一行中的4个数据一般是通过查询关键子keyWord从数据库中获取,本次则模拟静态数据 * 本次模拟的是输入关键字‘Li’产生的数据,但本次只是为了做范例,所以无论输入什么关键字,都将在浏览器中显示下面的4个数据 * */sb.append("suggestions:['Liberiag','Libyan Arab Jamahiriyaz','Liechtensteinf','Lithuania'],");/*下面一行数据是推荐关键字,可要可不要,建议不要,占网速啊*/sb.append("data:['LR','LY','LI','LT']");sb.append("}");out.write(sb.toString());}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}