比較簡單的模擬,文本框輸入CompanyName,然後
搜索SqlServer2000 裡NorthWind數據庫 SupplIErs表的CompanyName字段,
然後實現自動完成
四個文件
1 .AutoComplete.htm
[運行代碼] [復制到剪貼板] [ ± ]CODE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xHtml1-transitional.dtd">
<html XMLns="http://www.w3.org/1999/xHtml" >
<head>
<title>輸入自動完成</title>
<script language="Javascript">
//輸入信息的文本框
var txtInput;
//下拉表當前選中項的索引
var currentIndex = -1;
//初始化參數,和下拉表位置
function initPar()
{
txtInput = document.getElementById("txtCompanyName");
//設置下拉表 相對於 文本輸入框的位置
setPosition();
}
//設置下拉表 相對於 文本輸入框的位置
function setPosition()
{
var width = txtInput.offsetWidth;
var left = getLength("offsetLeft");
var top = getLength("offsetTop") + txtInput.offsetHeight;
divContent.style.left = left + "px";
divContent.style.top = top + "px";
divContent.style.width = width + "px";
}
//獲取對應屬性的長度
function getLength(attr)
{
var offset = 0;
var item = txtInput;
while (item)
{
offset += item[attr];
item = item.offsetParent;
}
return offset;
}
//自動完成
function autoComplete()
{
//如果按下 向上, 向下 或 回車
if (event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 13)
{
//選擇當前項
selItemByKey();
}
else //向服務器發送請求
{
//如果值為空
if (txtInput.value == "")
{
divContent.style.display='none';
return;
}
//恢復下拉選擇項為 -1
currentIndex = -1;
//開始請求
requestObj = new ActiveXObject("Microsoft.XMLHTTP");
requestObj.onreadystatechange = displayResult;
requestObj.open("POST", "AutoComplete.ASPx?ts=" + new Date().toLocaleString(), true);
requestObj.send(txtInput.value);
}
}
//顯示結果
function displayResult()
{
if (requestObj.readyState == 4)
{
showData();
divContent.style.display = "";
}
}
//顯示服務器返回的結果 ,並形成下拉表
function showData()
{
//獲取數據
var doc = new ActiveXObject("MSXML2.DOMDocument.3.0");
doc.loadXML(requestObj.responseText);
//顯示數據的xslt
var docStyle = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
docStyle.async = false;
docStyle.load("list.xslt");
var docTemplate = new ActiveXObject("MSXML2.XSLTemplate");
docTemplate.stylesheet = docStyle;
//通過xslt轉換XML數據
var processor = docTemplate.createProcessor();
processor.input = doc;
processor.transform();
var res = processor.output;
//顯示轉後後的結果
divContent.innerHtml = res;
}
//通過鍵盤選擇下拉項
function selItemByKey()
{
//下拉表
var tbl = document.getElementById("tblContent");
if (!tbl)
{
return;
}
//下拉表的項數
var maxRow = tbl.rows.length;
//向上
if (event.keyCode == 38 && currentIndex > 0)
{
currentIndex--;
}
//向下
else if (event.keyCode == 40 && currentIndex < maxRow-1)
{
currentIndex++;
}
//回車
else if (event.keyCode == 13)
{
selValue();
return;
}
clearColor();
txtInput.value = tbl.rows[currentIndex].innerText;
//設置當前項背景顏色為blue 標記選中
tbl.rows[currentIndex].style.backgroundColor = "InfoBackground";
}
//清除下拉項的背景顏色
function clearColor()
{
var tbl = document.getElementById("tblContent");
for (var i = 0; i < tbl.rows.length; i++)
{
tbl.rows[i].style.backgroundColor = "";
}
}
//選擇下拉表中當前項的值 ,用於按回車或鼠標單擊選中當前項的值
function selValue()
{
if (event.keyCode != 13)
{
var text = event.srcElement.innerText;
txtInput.value = text;
}
initList();
}
//文本框失去焦點時 設置下拉表可見性
function setDisplay()
{
//獲取當前活動td的表格
if (document.activeElement.tagName == "TD")
{
var tbl = document.activeElement.parentElement.parentElement.parentElement;
//如果不是下拉表,則隱藏 下拉表
if (tbl.id != "tblContent")
{
initList();
}
return;
}
initList();
}
function initList()
{
divContent.style.display='none';
divContent.innerHtml = "";
currentIndex = -1;
}
</script>
</head>
<body >
CompanyName<input type="text" id="txtCompanyName" onkeyup="autoComplete()" onblur="setDisplay();" style="width:400px"/>
<!-- 顯示下拉表的div-->
<div id="divContent" style="display:none; position:absolute; ">
</div>
</body>
</Html>
AutoComplete.ASPx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoComplete.ASPx.cs" Inherits="AJaxBaseHome.AutoComplete" %>
AutoComplete.ASPx.cs
[運行代碼] [復制到剪貼板] [ ± ]CODE:
using System;
using System.Data;
using System.Data.SqlClIEnt;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
namespace AJaxBaseHome
{
public partial class AutoComplete : System.Web.UI.Page
{
private static string conString = WebConfigurationManager.ConnectionStrings["myData"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
string input = GetInput();
Response.Write(GetCompanyName(input));
}
//獲取輸入的字符串
private string GetInput()
{
Stream s = Request.InputStream;
int count = 0;
byte[] buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
while ((count = s.Read(buffer, 0, 1024)) > 0)
{
builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
}
return builder.ToString();
}
private string GetCompanyName(string input)
{
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand command = new SqlCommand("select * from supplIErs where CompanyName like @Name", con);
command.Parameters.Add(new SqlParameter("@name", input + "%"));
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds.GetXML();
}
}
}
}
xslt文件 用於顯示XML數據
[運行代碼] [復制到剪貼板] [ ± ]CODE:
<?XML version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" XMLns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="Html"/>
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="NewDataSet">
<table id="tblContent" style="background-color:GrayText">
<xsl:for-each select="Table">
<tr>
<!--td中單擊時選擇當前值, 鼠標在上時更改行背景顏色,鼠標離開後清除背景顏色-->
<td style="cursor:hand" >
<xsl:value-of select="CompanyName"/>
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>