UML软件工程组织

Ajax基础教程 - 4.6 创建工具提示
作者:(美)阿斯利森 舒塔   出处:csdn

4.6 创建工具提示

我们见过许多使用Ajax的应用,到目前为止,我们认为最有意思的是DVD租借服务Netflix。当浏览Netflix中的各个选择时,会看到各类最新影片的相关图片和文字。当把鼠标停在一个给定影片的图片上时,就会看到更多的信息(见图4-12)。尽管不使用Ajax也能达到这个效果,但第一次获取页面时要纳入大量可能永远也不会用到的信息。通过使用Ajax,只会在需要时发送所需的信息。

虽然我们的例子做得没有这么漂亮,但你能从中了解到如何提供自己的动态工具提示信息。客户端代码相当简单(见代码清单4-11)。这里最有意思的是calculateOffset()方法。在理想情况下,可以依赖于当前元素的offset属性。不过,如果要跨浏览器,这样做不一定可行,不同浏览器上的偏移量可能不同。但是,你可以访问DOM来生成一个准确的偏移量,并使用这个偏移量来放置动态内容。这个例子中有一个简单的表,其中包含著名的高尔夫球场,当用户把鼠标停在表中某个单元格上时,会显示一些额外的信息。

代码清单4-11 toolTip.html

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

 

<html>

  <head>

    <title>Ajax Tool Tip</title>

    <script type="text/javascript">

        var xmlHttp;

        var dataDiv;

        var dataTable;

        var dataTableBody;

        var offsetEl;

 

        function createXMLHttpRequest() {

            if (window.ActiveXObject) {

                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

            }

            else if (window.XMLHttpRequest) {

                xmlHttp = new XMLHttpRequest();

            }

        }

 

        function initVars() {

            dataTableBody = document.getElementById("courseDataBody");

            dataTable = document.getElementById("courseData");

            dataDiv = document.getElementById("popup");

        }

 

        function getCourseData(element) {

            initVars();

            createXMLHttpRequest();

            offsetEl = element;

            var url = "ToolTipServlet?key=" + escape(element.id);

 

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

            xmlHttp.onreadystatechange = callback;

            xmlHttp.send(null);

        }

 

        function callback() {

            if (xmlHttp.readyState == 4) {

                if (xmlHttp.status == 200) {

                    setData(xmlHttp.responseXML);

                }

            }

        }

 

        function setData(courseData) {

            clearData();

            setOffsets();

            var length =

                     courseData.getElementsByTagName("length")[0].firstChild.data;

            var par = courseData.getElementsByTagName("par")[0].firstChild.data;

 

            var row, row2;

            var parData = "Par: " + par

            var lengthData = "Length: " + length;

 

            row = createRow(parData);

            row2 = createRow(lengthData);

 

            dataTableBody.appendChild(row);

            dataTableBody.appendChild(row2);

        }

 

        function createRow(data) {

            var row, cell, txtNode;

            row = document.createElement("tr");

            cell = document.createElement("td");

 

            cell.setAttribute("bgcolor", "#FFFAFA");

            cell.setAttribute("border", "0");

 

            txtNode = document.createTextNode(data);

            cell.appendChild(txtNode);

            row.appendChild(cell);

 

            return row;

        }

 

        function setOffsets() {

            var end = offsetEl.offsetWidth;

            var top = calculateOffsetTop(offsetEl);

            dataDiv.style.border = "black 1px solid";

            dataDiv.style.left = end + 15 + "px";

            dataDiv.style.top = top + "px";

        }

 

        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 clearData() {

            var ind = dataTableBody.childNodes.length;

            for (var i = ind - 1; i >= 0 ; i--) {

                dataTableBody.removeChild(dataTableBody.childNodes[i]);

            }

            dataDiv.style.border = "none";

        }

    </script>

  </head>

  <body>

    <h1>Ajax Tool Tip Example</h1>

    <h3>Golf Courses</h3>

    <table id="courses" bgcolor="#FFFAFA" border="1"

                                            cellspacing="0" cellpadding="2"/>

        <tbody>

            <tr><td id="1" onmouseover="getCourseData(this);"

                          onmouseout="clearData();">Augusta National</td></tr>

            <tr><td id="2" onmouseover="getCourseData(this);"

                          onmouseout="clearData();">Pinehurst No. 2</td></tr>

            <tr><td id="3" onmouseover="getCourseData(this);"

                          onmouseout="clearData();">

                          St. Andrews Links</td></tr>

            <tr><td id="4" onmouseover="getCourseData(this);"

                          onmouseout="clearData();">Baltusrol Golf Club</td></tr>

        </tbody>

    </table>

    <div style="position:absolute;" id="popup">

        <table id="courseData" bgcolor="#FFFAFA" border="0"

                                                cellspacing="2" cellpadding="2"/>

            <tbody id="courseDataBody"></tbody>

        </table>

    </div>

 

  </body>

</html>

要记住,在生产环境中,可能会从某种数据库获取额外的信息,而且servlet中可能不会有内部类!代码清单4-12显示了ToolTipServlet.java。

代码清单4-12 ToolTipServlet.java

package ajaxbook.chap4;

 

import java.io.*;

import java.util.HashMap;

import java.util.Map;

 

import javax.servlet.*;

import javax.servlet.http.*;

 

public class ToolTipServlet extends HttpServlet {

 

    private Map courses = new HashMap();

 

    public void init(ServletConfig config) throws ServletException {

        CourseData augusta = new CourseData(72, 7290);

        CourseData pinehurst = new CourseData(70, 7214);

        CourseData standrews = new CourseData(72, 6566);

        CourseData baltusrol = new CourseData(70, 7392);

        courses.put(new Integer(1), augusta);

        courses.put(new Integer(2), pinehurst);

        courses.put(new Integer(3), standrews);

        courses.put(new Integer(4), baltusrol);

    }

 

    /** Handles the HTTP <code>GET</code> method.

     * @param request servlet request

     * @param response servlet response

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

        Integer key = Integer.valueOf(request.getParameter("key"));

        CourseData data = (CourseData) courses.get(key);

 

        PrintWriter out = response.getWriter();

 

        response.setContentType("text/xml");

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

 

        out.println("<response>");

        out.println("<par>" + data.getPar() + "</par>");

        out.println("<length>" + data.getLength() + "</length>");

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

        out.close();

    }

 

private class CourseData {

        private int par;

        private int length;

 

        public CourseData(int par, int length) {

            this.par = par;

            this.length = length;

        }

 

        public int getPar() {

            return this.par;

        }

 

        public int getLength() {

            return this.length;

        }

    }

}

图4-13显示了实际运行的工具提示。

图4-13 Ajax工具提示示例

上一页     首页    下一页

 

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