autoComplete
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax Auto Complete</title>
<style type="text/css">
.mouseOut
{
background: #708090;
color: #FFFAFA;
}
.mouseOver
{
background: #FFFAFA;
color:#000000;
}
</style>
<script type="text/javascript">
var xmlHttp;
var completeDiv;
var inputField;
var nameTable;
var nameTableBody;
function createXMLHttpRequest()
{
if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
}
function initVars()
{
inputField = document.getElementById("names");//表示文本框
nameTable = document.getElementById("name_table");//表示表格
completeDiv = document.getElementById("popup");//表示div
nameTableBody = document.getElementById("name_table_body");//表示tbody
}
function findNames()
{
initVars();//初始化变量
if(inputField.value.length > 0)//表示文本框中输入了东西
{
createXMLHttpRequest();//创建XMLHttpRequest对象
var url = "/AjaxDemo/servlet/AutoCompleteServlet?names=" + escape(inputField.value);
xmlHttp.open("GET",url,true);//建立对服务器的连接
xmlHttp.onreadystatechange = callback;//当XMLHttpRequest对象状态发生改变的时候,设置回调函数
xmlHttp.send(null);//发送异步请求
}else
{
clearNames();//清除信息
}
}
function callback()//回调函数
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
setNames(xmlHttp.responseXML.getElementsByTagName("name"));
}else if(xmlHttp.status == 204)
{
clearNames();
}
}
}
function setNames(the_names)
{
clearNames();
var size = the_names.length;
setOffsets();
var row, cell, txtNode;
for(var i = 0; i < size; i++)
{
var nextNode = the_names[i].firstChild.data;
row = document.createElement("tr");//创建tr节点
cell = document.createElement("td");//创建td节点
cell.onmouseout = function() {this.className = 'mouseOver';};
cell.onmouseover = function() {this.className = 'mouseOut';};
cell.setAttribute("bgcolor","#FFFAFA");//设置背景色
cell.setAttribute("border","0");//设置边框
cell.onclick = function() {populateName(this);};
txtNode = document.createTextNode(nextNode);//获得文本节点
cell.appendChild(txtNode);
row.appendChild(cell);
nameTableBody.appendChild(row);
}
}
function setOffsets()
{
var end = inputField.offsetWidth;
var left = calculateOffsetLeft(inputField);
var top = calculateOffsetTop(inputField) + inputField.offsetHeight;
completeDiv.style.border = "black 1px solid";
completeDiv.style.left = left + "px";
completeDiv.style.top = top + "px";
nameTable.style.width = end + "px";
}
function calculateOffsetLeft(field)
{
return calculateOffset(field,"offsetLeft");
}
function calculateOffsetTop(field)
{
return calculateOffset(field,"offsetTop");
}
function calculateOffset(field,attr)
{
var offset = 0;
while(field)
{
offset += field[attr];
field = field.offsetParent;
}
return offset;
}
function populateName(cell)
{
inputField.value = cell.firstChild.nodeValue;
clearNames();
}
function clearNames()
{
var ind = nameTableBody.childNodes.length;
for(var i = ind - 1; i >= 0; i--)
{
nameTableBody.removeChild(nameTableBody.childNodes[i]);
}
completeDiv.style.border = "none";
}
</script>
</head>
<body>
<h1>Ajax Auto Complete Example</h1>
Names: <input type="text" size = "20" id="names" onkeyup="findNames();" style="height:20px;"/>
<div style="position:absolute;" id="popup">
<table id="name_table" bgcolor="#FFFAFA" border="0" cellspacing="0" cellpadding="0">
<tbody id="name_table_body"></tbody>
</table>
</div>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax Auto Complete</title>
<style type="text/css">
.mouseOut
{
background: #708090;
color: #FFFAFA;
}
.mouseOver
{
background: #FFFAFA;
color:#000000;
}
</style>
<script type="text/javascript">
var xmlHttp;
var completeDiv;
var inputField;
var nameTable;
var nameTableBody;
function createXMLHttpRequest()
{
if(window.ActiveXObject)
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
xmlHttp = new XMLHttpRequest();
}
}
function initVars()
{
inputField = document.getElementById("names");//表示文本框
nameTable = document.getElementById("name_table");//表示表格
completeDiv = document.getElementById("popup");//表示div
nameTableBody = document.getElementById("name_table_body");//表示tbody
}
function findNames()
{
initVars();//初始化变量
if(inputField.value.length > 0)//表示文本框中输入了东西
{
createXMLHttpRequest();//创建XMLHttpRequest对象
var url = "/AjaxDemo/servlet/AutoCompleteServlet?names=" + escape(inputField.value);
xmlHttp.open("GET",url,true);//建立对服务器的连接
xmlHttp.onreadystatechange = callback;//当XMLHttpRequest对象状态发生改变的时候,设置回调函数
xmlHttp.send(null);//发送异步请求
}else
{
clearNames();//清除信息
}
}
function callback()//回调函数
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
setNames(xmlHttp.responseXML.getElementsByTagName("name"));
}else if(xmlHttp.status == 204)
{
clearNames();
}
}
}
function setNames(the_names)
{
clearNames();
var size = the_names.length;
setOffsets();
var row, cell, txtNode;
for(var i = 0; i < size; i++)
{
var nextNode = the_names[i].firstChild.data;
row = document.createElement("tr");//创建tr节点
cell = document.createElement("td");//创建td节点
cell.onmouseout = function() {this.className = 'mouseOver';};
cell.onmouseover = function() {this.className = 'mouseOut';};
cell.setAttribute("bgcolor","#FFFAFA");//设置背景色
cell.setAttribute("border","0");//设置边框
cell.onclick = function() {populateName(this);};
txtNode = document.createTextNode(nextNode);//获得文本节点
cell.appendChild(txtNode);
row.appendChild(cell);
nameTableBody.appendChild(row);
}
}
function setOffsets()
{
var end = inputField.offsetWidth;
var left = calculateOffsetLeft(inputField);
var top = calculateOffsetTop(inputField) + inputField.offsetHeight;
completeDiv.style.border = "black 1px solid";
completeDiv.style.left = left + "px";
completeDiv.style.top = top + "px";
nameTable.style.width = end + "px";
}
function calculateOffsetLeft(field)
{
return calculateOffset(field,"offsetLeft");
}
function calculateOffsetTop(field)
{
return calculateOffset(field,"offsetTop");
}
function calculateOffset(field,attr)
{
var offset = 0;
while(field)
{
offset += field[attr];
field = field.offsetParent;
}
return offset;
}
function populateName(cell)
{
inputField.value = cell.firstChild.nodeValue;
clearNames();
}
function clearNames()
{
var ind = nameTableBody.childNodes.length;
for(var i = ind - 1; i >= 0; i--)
{
nameTableBody.removeChild(nameTableBody.childNodes[i]);
}
completeDiv.style.border = "none";
}
</script>
</head>
<body>
<h1>Ajax Auto Complete Example</h1>
Names: <input type="text" size = "20" id="names" onkeyup="findNames();" style="height:20px;"/>
<div style="position:absolute;" id="popup">
<table id="name_table" bgcolor="#FFFAFA" border="0" cellspacing="0" cellpadding="0">
<tbody id="name_table_body"></tbody>
</table>
</div>
</body>
</html>
AutoCompleteServlet
package cn.Ajax.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class AutoCompleteServlet extends HttpServlet {
private List<String> names = new ArrayList<String>();
@Override//初始化names
public void init(ServletConfig config) throws ServletException {
names.add("Ajax");
names.add("Ajax Basic");
names.add("Ajax in action");
names.add("Ajax Design");
names.add("Ajax Programming");
names.add("Ajax Development");
names.add("Mike");
names.add("Maricle");
names.add("MagicCoder");
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String prefix = request.getParameter("names");
NameService service = NameService.getInstance(names);
List<String> matching = service.findNames(prefix);
if(matching.size() > 0){
PrintWriter out = response.getWriter();
response.setContentType("text/xml;charset=gbk");
response.setHeader("Cache-Control", "no-cache");
out.println("<response>");
Iterator<String> iter = matching.iterator();
while (iter.hasNext()) {
String name = iter.next();
out.println("<name>"+name+"</name>");
}
out.println("</response>");
matching = null;
service = null;
out.close();
}else{
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package cn.Ajax.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class AutoCompleteServlet extends HttpServlet {
private List<String> names = new ArrayList<String>();
@Override//初始化names
public void init(ServletConfig config) throws ServletException {
names.add("Ajax");
names.add("Ajax Basic");
names.add("Ajax in action");
names.add("Ajax Design");
names.add("Ajax Programming");
names.add("Ajax Development");
names.add("Mike");
names.add("Maricle");
names.add("MagicCoder");
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String prefix = request.getParameter("names");
NameService service = NameService.getInstance(names);
List<String> matching = service.findNames(prefix);
if(matching.size() > 0){
PrintWriter out = response.getWriter();
response.setContentType("text/xml;charset=gbk");
response.setHeader("Cache-Control", "no-cache");
out.println("<response>");
Iterator<String> iter = matching.iterator();
while (iter.hasNext()) {
String name = iter.next();
out.println("<name>"+name+"</name>");
}
out.println("</response>");
matching = null;
service = null;
out.close();
}else{
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
NameService
package cn.Ajax.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class NameService {
private List<String> names;
private NameService(List<String> list)//单例模式
{
this.names = list;
}
public static NameService getInstance(List<String> list)//获得该对象
{
return new NameService(list);
}
public List<String> findNames(String prefix)//根据文本框输入的值进行前缀比对,比对正确加入到matches集合中
{
String prefix_upper = prefix.toUpperCase();
List<String> matches = new ArrayList<String>();
Iterator<String> iter = names.iterator();
while (iter.hasNext()) {
String name = iter.next();
String name_upper_case = name.toUpperCase();
if(name_upper_case.startsWith(prefix_upper)){
matches.add(name);
}
}
return matches;
}
}
package cn.Ajax.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class NameService {
private List<String> names;
private NameService(List<String> list)//单例模式
{
this.names = list;
}
public static NameService getInstance(List<String> list)//获得该对象
{
return new NameService(list);
}
public List<String> findNames(String prefix)//根据文本框输入的值进行前缀比对,比对正确加入到matches集合中
{
String prefix_upper = prefix.toUpperCase();
List<String> matches = new ArrayList<String>();
Iterator<String> iter = names.iterator();
while (iter.hasNext()) {
String name = iter.next();
String name_upper_case = name.toUpperCase();
if(name_upper_case.startsWith(prefix_upper)){
matches.add(name);
}
}
return matches;
}
}