ajax实现文本框自动补全

   下面是利用ajax完成的文本框自动补全,数据转换格式用的是json,代码中的javacommon.ijdbc是自己写的jdbc的封装,大可换成别的。

  

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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">
	var compUsername = function() {
		//1.创建XMLHttpRequest对象
		var xmlRequest = new XMLHttpRequest();
		//alert(xmlRequest);
		//2.发送请求
		var username = document.getElementById("username").value;
		if (username == '') {
			return;
		}
		xmlRequest.open("POST", "/myWeb/CompleteUsername", true); //第三个参数必须 
		xmlRequest.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded");
		xmlRequest.send("username=" + username + "&r=" + new Date());

		xmlRequest.onreadystatechange = function() {
			if (xmlRequest.readyState == 4) {//如果响应状态为4,说明响应成功
				var resp = xmlRequest.responseText;
				var rst = eval("(" + resp + ")");//转换json字符串为js对象
				var nameArray = rst.list;
				var i;
				var nameList = document.getElementById("nameList");
				nameList.innerHTML = '';
				for (i = 0; i < nameArray.length; i++) {
					//alert(nameArray[i]);
					var newP = document.createElement("p");
					newP.innerHTML = nameArray[i];
					newP.onclick = function() { //给每一个添加点击事件
						//alert();
						document.getElementById("username").value = this.innerHTML;
						nameList.style.display = 'none';
					};
					nameList.appendChild(newP);
				}
				nameList.style.display = 'block';
				//解析
				//alert(resp);

			}
		};
	};
	function selectName(html) {
		document.getElementById("username").value = html;
		var nameList = document.getElementById("nameList");
		nameList.style.display = 'none';
	}
</script>
</head>
<body>
	用户名:
	<input type="text" id="username" name="username"
		onkeyup="compUsername()">
	<div id="nameList"
		style="width: 200px; height: auto; position: relative; left: 65px; top: -18px; display: none;">
		<p onclick="selectName(this.innerHTML)">Abel1</p>
	</div>
</body>
</html>

 查询数据用的是一个servlet

  

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import javacommon.ijdbc.IJdbcOperation;
import javacommon.ijdbc.impl.JdbcUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/CompleteUsername")
public class CompleteUsername extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    String username = request.getParameter("username");
	    //查询类似的username
	    String sql = "select last_name from employees where last_name like '"+username+"%'";
	    IJdbcOperation operation = JdbcUtils.getInstance();
	    try {
            ResultSet rs = operation.queryForResultSet(sql);
            StringBuilder sb = new StringBuilder("{\"list\":[");
            while (rs.next()) {
                String _un = rs.getString(1);
                sb.append("\"").append(_un).append("\",");
            }
            int index = sb.length()-1;
            if (sb.charAt(index)==',') {
                sb.deleteCharAt(index);   //删除多余的逗号
            }
            sb.append("]}");
            PrintWriter writer = response.getWriter();
            writer.write(sb.toString());
            writer.flush();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}
}

相关推荐