DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
用 Ajax 打造搜尋框即時提示(ASP 版完整實作)
編輯:AJAX詳解     

這是一個以 ASP 實作的輸入提示範例:使用者在輸入框打字時,後端即時回傳符合的關鍵字清單,點選任一項即可填入。

前台頁面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>文本框输入提示</title>
<style type="text/css">
.keyWord {
    width: 150px; height: 20px;
    border: #0066FF 1px solid;
}
#keytishi {
    width: 150px; height: auto;
    border: #0066FF 1px solid;
    position: absolute;
    display: none;
}
#keytishi ul { margin: 0; }
#keytishi ul li {
    margin: 0; list-style-type: none;
    line-height: 16px; height: 16px;
    font-size: 12px; padding: 2px;
}
#keytishi ul li a {
    display: block; width: 150px; height: 16px;
    text-decoration: none;
}
#keytishi ul li a:hover { background-color: #0099FF; }
</style>
<script type="text/javascript">
// 建立 XMLHttpRequest 物件
var XMLhttp;
try {
    XMLhttp = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
    try {
        XMLhttp = new ActiveXObject('Microsoft.XMLHTTP');
    } catch (e) {
        try {
            XMLhttp = new XMLHttpRequest();
        } catch (e) {}
    }
}

function getKeyWord() {
    var obj = document.getElementById("search");
    if (obj.value == "") { return; }

    var top = 0, left = 0;
    while (obj) {
        // 逐層累加,得到輸入框在頁面中的絕對位置
        top  += obj["offsetTop"];
        left += obj["offsetLeft"];
        obj = obj.offsetParent;
    }

    XMLhttp.open("get", "input.asp?keyWord=" +
                 document.getElementById("search").value, true);
    XMLhttp.onreadystatechange = function () {
        if (XMLhttp.readyState == 4) {
            if (XMLhttp.status == 200) {
                if (XMLhttp.responseText != "") {
                    document.getElementById("keytishi").innerHTML =
                        unescape(XMLhttp.responseText);
                    document.getElementById("keytishi").style.left = left + "px";
                    document.getElementById("keytishi").style.top = (top + 25) + "px";
                    document.getElementById("keytishi").style.display = "block";
                } else {
                    document.getElementById("keytishi").innerHTML = "";
                    document.getElementById("keytishi").style.display = "none";
                }
            }
        }
    }
    XMLhttp.setRequestHeader("If-Modified-Since", "0");
    XMLhttp.send(null);
}

function input(str) {
    document.getElementById("search").value = str;
    document.getElementById("keytishi").innerHTML = "";
    document.getElementById("keytishi").style.display = "none";
}
</script>
</head>
<body>
<input type="text" class="keyWord" id="search" name="search"
       onkeyup="getKeyWord();" onclick="getKeyWord();" />
<div id="keytishi"</div><!-- 提示層 -->
</body>
</html>

後台程式 input.asp

<%@ LANGUAGE="VBSCRIPT" CODEPAGE="65001" %>
<!--#include file="conn.asp"-->
<%
dim rs, sql, keyWords

keyWords = Request("keyWord")

Set rs = Server.CreateObject("ADODB.Recordset")
sql = "select * from king_test where keyWord like '%" & keyWords & "%'"
rs.open sql, conn, 1, 1

if not (rs.bof and rs.eof) then
    Response.Write("<ul>")
    do while not rs.eof
%>
<li><a href="javascript:void(null);"
       onclick="input('<%Response.Write(escape(rs("keyWord")))%>');"><%=
       escape(rs("keyWord"))%></a></li>
<%
        rs.movenext
    loop
    Response.Write("</ul>")
end if

rs.close
set rs = nothing
conn.close
Set conn = nothing
%>

幾個實作細節

escape 與 unescape 這組配對是用來編解碼的,目的是避免中文出現亂碼。此範例已在 XP 搭配 IE6、IE7 與 Firefox 測試通過。

位置計算那段 while 迴圈,是透過逐層累加 offsetTop/offsetLeft 取得輸入框的絕對座標,提示層才能準確貼在輸入框下方。這種做法在樣式單純時有效,但遇到 position 或 transform 較複雜的版面就容易失準,實務上改用 CSS 讓提示層相對於一個 positioned 容器定位會更穩健。

最後要特別提醒:範例中的 SQL 直接把使用者輸入的字串拼接進查詢語句,這是典型的 SQL 注入弱點。正式環境請改用參數化查詢(如 ADODB.Command 的 Parameters 集合),並對回傳內容做 HTML 編碼後再輸出,才能同時避免注入與 XSS。示範程式可以偷懶,上線的程式不行。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved