使用Ajax实现自动完成

使用Ajax实现自动完成
1.初始化:使用DIV作为提示框,初始化时无边框,背景与网页背景一致;
2.在文本框输入时,触发onKeyUp事件,在数据库中查询以用户输入字符串开头的所有字符串,返回给客户端;
3.客户端接收到响应后清除提示框,将返回的字符串加入到D提示框中,边框设为1,根据文本框的位置设定提示框的位置;
4.鼠标点击提示框中的字符串时,改变背景色和前景色,实现选中效果,将字符串设置到文本框中,通过上下方向键可以循环选择;



autoComplete.html:
程序代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html onclick="clearTip();">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>AutoComplete</title>
        <style>
            #word {
                width:150px;
            }
            #tip {
                position:absolute;
                top:0px;
                left:0px;
                width:154px;
                font-size:12px;
            }
            .mouseOut {
                color:#000000;
                background-color:#FFFFFF;
            }
            .mouseOver {
                color:#FFFFFF;
                background-color:#0000FF;
            }
        </style>
        <script src="js/autoComplete.js"></script>
    </head>
    <body>
        <h1>AutoComplete</h1>
        <br />
        <input id="word" type="text" onKeyUp="doSearch();" onKeyDown="parseKey();"/>
        <div id="tip">
            <table id="tab" cellpadding="0" cellspacing="0">
                <tbody id="tb"></tbody>
            </table>
        </div>
    </body>
</html>


js/autoComplete.js:
程序代码

var xmlHttp;
var selectedIndex = 0;

function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}

function doSearch() {
    var e = window.event ? window.event : e;
    if (e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 13) {
        createXMLHttpRequest();
        xmlHttp.onreadystatechange = callback;
        var word = document.getElementById("word").value;
        var url = "autoComplete.mgc?word=" + word + "×tamp=" + new Date().getTime();
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
}

function callback() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            parseResult();
        } else {
            clearTip();
        }
    }
}

function clearTip() {
    tip.style.border = "none";
    var tb = document.getElementById("tb");
    while (tb.hasChildNodes()) {
        tb.removeChild(tb.firstChild);
    }
}

function parseResult() {
    var xmlDoc = xmlHttp.responseXML;
    var words = xmlDoc.getElementsByTagName("word");
    clearTip();
    setPosition();
    createTip(words);
}

function createTip(words) {
    var tip = document.getElementById("tip");
    var word = document.getElementById("word");
    var tb = document.getElementById("tb");
    for (var i = 0; i < words.length; i++) {
        var row = document.createElement("tr");
        var cell = document.createElement("td");
        cell.style.width = (word.offsetWidth - 2) + "px";
        cell.style.padding = "2px";
        cell.onmouseout = function() {this.className='mouseOut';};
        cell.onmouseover = function() {this.className='mouseOver';};
        cell.onclick = function() {word.value = this.firstChild.nodeValue;clearTip();};
        var content = document.createTextNode(words[i].firstChild.nodeValue);
        cell.appendChild(content);
        row.appendChild(cell);
        tb.appendChild(row);
    }
    tip.style.border = "#000000 1px solid";
    selectedIndex = 0;
}

function setPosition() {
    var word = document.getElementById("word");
    var top = getOffsetTOP(word);
    var left = getOffsetLeft(word);
    var tip = document.getElementById("tip");
    tip.style.top = top + word.offsetHeight + "px";
    tip.style.left = left + "px";
}

function getOffsetTOP(elem) {
    var top = 0;
    while (elem) {
        top += elem.offsetTop;
        elem = elem.offsetParent;
    }
    return top;
}

function getOffsetLeft(elem) {
    var left = 0;
    while (elem) {
        left += elem.offsetLeft;
        elem = elem.offsetParent;
    }
    return left;
}

function parseKey() {
    var e = window.event ? window.event : e;
    if (e.keyCode == 40) {
        var rows = document.getElementsByTagName("tr");
        if (rows.length > 1) {
            var word = document.getElementById("word");
            word.value = rows[selectedIndex].firstChild.firstChild.nodeValue;
            rows[selectedIndex].firstChild.className = "mouseOver";
            var lastIndex = selectedIndex - 1;
            if (lastIndex < 0) {
                lastIndex = rows.length - 1;
            }
            rows[lastIndex].firstChild.className = "mouseOut";
            if ((++selectedIndex) >= rows.length) {
                selectedIndex = 0;
            }
        } else if (rows.length == 1) {
            var word = document.getElementById("word");
            word.value = rows[0].firstChild.firstChild.nodeValue;
            rows[0].firstChild.className = "mouseOver";
        }
    } else if (e.keyCode == 38) {
        var rows = document.getElementsByTagName("tr");
        if (rows.length > 1) {
            var word = document.getElementById("word");
            selectedIndex = selectedIndex - 1;
            if (selectedIndex < 0) {
                selectedIndex = rows.length - 1;
            }
            word.value = rows[selectedIndex].firstChild.firstChild.nodeValue;
            rows[selectedIndex].firstChild.className = "mouseOver";
            var lastIndex = selectedIndex + 1;
            if (lastIndex >= rows.length) {
                lastIndex = 0;
            }
            rows[lastIndex].firstChild.className = "mouseOut";
        } else if (rows.length == 1) {
            var word = document.getElementById("word");
            word.value = rows[0].firstChild.firstChild.nodeValue;
            rows[0].firstChild.className = "mouseOver";
        }
    } else if (e.keyCode == 13) {
        clearTip();
    }
}


AutoComplete.java:
程序代码

package cn.edu.ahau.mgc.ajax.autocomplete;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AutoComplete extends HttpServlet {
   
    List<String> words = new ArrayList<String>();

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

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String word = request.getParameter("word").trim();
        List<String> results = new ArrayList<String>();
        if (word != null && !"".equals(word)) {
            results = this.search(word);
        }
        if (results.size() == 0) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            response.setContentType("text/xml");
            response.setHeader("Cache-Control", "no-cache");
            StringBuffer xml = new StringBuffer();
            xml.append("<words>");
            for (Iterator<String> iterator = results.iterator(); iterator.hasNext();) {
                String str = iterator.next();
                xml.append("<word>" + str + "</word>");
            }
            xml.append("</words>");
            PrintWriter out = response.getWriter();
            out.print(xml);
        }
    }

    private List<String> search(String word) {
        List<String> results = new ArrayList<String>();
        for (Iterator<String> iterator = words.iterator(); iterator.hasNext();) {
            String str = iterator.next();
            if (str.toUpperCase().startsWith(word.toUpperCase())) {
                results.add(str);
            }
        }
        return results;
    }

    @Override
    public void init() throws ServletException {
        super.init();
        this.initData();
    }

    private void initData() {
        words.add("J2SE");
        words.add("J2ME");
        words.add("J2EE");
        words.add("Java");
        words.add("JSP");
        words.add("Servlet");
        words.add("Oracle");
        words.add("Tomcat");
        words.add("AAAAAAA");
        words.add("BBBBBBB");
        words.add("CCCCCCC");
        words.add("DDDDDDD");
        words.add("EEEEEEE");
        words.add("FFFFFFF");
        words.add("GGGGGGG");
    }

}


web.xml:
程序代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>AutoComplete</servlet-name>
    <servlet-class>cn.edu.ahau.mgc.ajax.autocomplete.AutoComplete</servlet-class>
  </servlet>




  <servlet-mapping>
    <servlet-name>AutoComplete</servlet-name>
    <url-pattern>/autoComplete.mgc</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

你可能感兴趣的:(oracle,xml,Ajax,jsp,servlet)