UML软件工程组织

Ajax基础教程 - 4.9 提供自动完成
作者:(美)阿斯利森 舒塔   出处:csdn

4.9 提供自动完成

我们遇到的最受欢迎的功能之一就是自动完成。许多人都使用过Intuit的Quicken之类的工具,并对其注册表的功能很是着迷,它的注册表能根据以前的注册项填入信息。这就使得数据输入更快、更容易,而且不容易出错。对于胖客户应用,增加这个功能可能很容易,但是Web应用长期以来一直都没有这个特性[1]。不过,Google在其beta实验区推出Google Suggest后,证明了自动完成对于Web应用并非遥不可及。

Google Suggest实在让人赞叹不已(见图4-16)。它不仅很好地放置了下拉区,还会在输入框中自动插入最有可能的答案,并将非用户键入的部分置灰,在下拉区中甚至还能使用向上和向下箭头。由于为给定项提供了一些结果,用户就能更清楚地认识到具体完成搜索时可能会得到的结果。

许多网站都对Google Suggest做了剖析(可以在google上查Google Suggest!)。代码清单4-17所示的例子比不上Google Suggest那么丰富,但你确实能从中了解到利用Ajax可以做些什么。需要注意,在这个例子中,callback()函数除了查找一般的返回码200,还会查找返回码204。204响应码指示服务器没有发回任何信息,利用个提示可以清空名字下拉区。你还会注意到,通过点记法为单元格设置鼠标事件,这一点在前面的“为什么不能用setAttribute方法来设置Delete按钮的事件处理程序?”旁注中已经解释过。重申一次,使用calculateOffset()方法来确定应该把数据放在哪个位置。

图4-16 Ajax为Google Suggest增色不少

代码清单4-17 autoComplete.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");

            nameTableBody = document.getElementById("name_table_body");

        }

 

        function findNames() {

            initVars();

            if (inputField.value.length > 0) {

                createXMLHttpRequest();

                var url = "AutoCompleteServlet?names=" + escape(inputField.value);

                xmlHttp.open("GET", url, true);

                xmlHttp.onreadystatechange = callback;

                xmlHttp.send(null);

            } else {

                clearNames();

            }

        }

 

        function callback() {

            if (xmlHttp.readyState == 4) {

                if (xmlHttp.status == 200) {

                    var name =

                             xmlHttp.responseXML

                            .getElementsByTagName("name")[0].firstChild.data;

                    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");

                cell = document.createElement("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:20;"/>

        <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>

服务器端代码模拟了命名服务的动态名字搜索功能。servlet中设置了一组名字,搜索委托给包含有查找逻辑的另一个类。注意,如果没有找到任何数据,要向客户返回响应,指示没有内容。代码清单4-18显示了AutoCompleteServlet.java,代码清单4-19是NameSer-
vice.java。

代码清单4-18 AutoCompleteServlet.java

package ajaxbook.chap4;

 

import java.io.*;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import javax.servlet.*;

import javax.servlet.http.*;

 

public class AutoCompleteServlet extends HttpServlet {

 

    private List names = new ArrayList();

 

    public void init(ServletConfig config) throws ServletException {

        names.add("Abe");

        names.add("Abel");

        names.add("Abigail");

        names.add("Abner");

        names.add("Abraham");

        names.add("Marcus");

        names.add("Marcy");

        names.add("Marge");

        names.add("Marie");

    }

 

protected void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

        String prefix = request.getParameter("names");

        NameService service = NameService.getInstance(names);

        List matching = service.findNames(prefix);

        if (matching.size() > 0) {

            PrintWriter out = response.getWriter();

 

            response.setContentType("text/xml");

            response.setHeader("Cache-Control", "no-cache");

 

            out.println("<response>");

            Iterator iter = matching.iterator();

            while(iter.hasNext()) {

                String name = (String) iter.next();

                out.println("<name>" + name + "</name>");

            }

            out.println("</response>");

            matching = null;

            service = null;

            out.close();

        } else {

            response.setStatus(HttpServletResponse.SC_NO_CONTENT);

        }

    }

}

代码清单4-19  NameService.java

package ajaxbook.chap4;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

 

public class NameService {

    private List names;

 

    /** Creates a new instance of NameService */

    private NameService(List list_of_names) {

        this.names = list_of_names;

    }

 

    public static NameService getInstance(List list_of_names) {

        return new NameService(list_of_names);

    }

 

    public List findNames(String prefix) {

        String prefix_upper = prefix.toUpperCase();

        List matches = new ArrayList();

        Iterator iter = names.iterator();

        while(iter.hasNext()) {

            String name = (String) iter.next();

            String name_upper_case = name.toUpperCase();

            if(name_upper_case.startsWith(prefix_upper)){

                boolean result = matches.add(name);

            }

        }

        return matches;

    }

}

图4-17显示了实际运行的自动完成示例。

图4-17 自动完成示例

 

上一页     首页    下一页

 

版权所有:UML软件工程组织