转自:http://www.cnblogs.com/tangself/archive/2011/07/27/2118447.html
<html>
<head><title>AutoComplete-Sample</title>
<style>
#auto_div{
position:absolute;
border-1px;
border:1px #808080 solid; }
</style>
<script src="js/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
//高亮的索引
var highLightIndex = -1;
//超时的标识(对用户连续快速按下键盘的事件做延时处理,只对用户在500ms内最后一次请求,让其生效)
var timeoutId;
$(document).ready(function () {
init();
$('#auto_txt').bind('keyup', processKeyup);
});
/**
* 处理键盘按下后弹起的事件
* @param event
*/
function processKeyup(event) {
var myEvent = event || windows.event;
var keyCode = myEvent.keyCode;
//输入是字母,或者退格键则需要重新请求
if ((keyCode >= 65 && keyCode <= 90) || keyCode == 8) {
//以下两行代码是为了防止用户快速输入导致频繁请求服务器
//这样便可以在用户500ms内快速输入的情况下,只请求服务器一次
//大大提高服务器性能
highLightIndex = -1;
clearTimeout(timeoutId);
timeoutId = setTimeout(processAjaxRequest, 100);
//处理上下键(up,down)
} else if (keyCode == 38 || keyCode == 40) {
processKeyUpAndDown(keyCode);
//按下了回车键
} else if (keyCode == 13) {
processEnter();
}
}
/***
* 初始化弹出框列表的位置,大小
*/
function init() {
$('#auto_div').hide();
var pos = $('#auto_txt').position();
var topPosition = pos.top + $('#auto_txt').height() + 7;
var leftPosition = pos.left;
$('#auto_div').offset({ top: topPosition, left: leftPosition });
$('#auto_div').width($('#auto_txt').width());
//$('#auto_div').css('position','absolute');
}
/**
* 处理Ajax请求
* @param data
*/
function processAjaxRequest() {
$.ajax({
type: "post", //http请求方法,默认:"post"
url: "/Office/GetSQ.ashx", //发送请求的地址
data: "reqWord=" + $('#auto_txt').val(),
success: processAjaxResponse
});
}
/**
* 处理Ajax回复
* @param data Ajax请求得到的返回结果为dom文档对象
*/
function processAjaxResponse(data) {
$('#auto_div').html('').show();
var words = data.split("-");
jQuery.each(words, function (i) {
var word_div = $("<div style='100%;'></div>");
word_div.html(words[i]);
word_div.hover(fnOver, fnOut);
word_div.click(getAutoText);
$('#auto_div').append(word_div);
});
}
/**
* 处理鼠标滑过
*/
function fnOver() {
//alert($(this));
changeToWhite();
$(this).css('background-color', 'pink');
//alert($(this).index());
highLightIndex = $(this).index();
//下面一行注释掉了,百度搜索也没这功能,就是鼠标移动时,跟着改变搜索框的内容
//$('#auto_txt').val($('#auto_div').children().eq(highLightIndex).html());
}
/**
* 处理鼠标移除
*/
function fnOut() {
$(this).css('background-color', 'white');
}
/**
* 得到自动填充文本
*/
function getAutoText() {
//有高亮显示的则选中当前选中当前高亮的文本
if (highLightIndex != -1) {
$('#auto_txt').val($(this).html());
$('#auto_div').html('').hide();
}
}
/**
* 处理按下Enter键
* @param keyCode
*/
function processEnter() {
if (highLightIndex != -1) {
$('auto_txt').val($('#auto_div').children().eq(highLightIndex).html());
$('#auto_div').html('').hide();
}
}
/**
* 处理按上下键的情况
*/
function processKeyUpAndDown(keyCode) {
var words = $('#auto_div').children();
var num = words.length;
if (num <= 0) return;
changeToWhite();
highLightIndex = ((keyCode != 38 ? num + 1 : num - 1) + highLightIndex) % num;
words.eq(highLightIndex).css('background-color', 'pink');
$('#auto_txt').val(words.eq(highLightIndex).html());
}
/**
* 如果有高亮的则把高亮变白
*/
function changeToWhite() {
if (highLightIndex != -1) {
$('#auto_div').children().eq(highLightIndex).css('background-color', 'white');
}
}
</script>
</head>
<body>
自动完成示例 <input type="text" id="auto_txt"><input type="button" value="提交">
<div style="border-1px;" id="auto_div"></div>
</body>
</html>
1,search.aspx(显示页面)
<!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" type="text/javascript">
//创建XMLHttpRequest对象
function createXMLHttpRequest() {
var obj;
if(window.XMLHttpRequest) { //Mozilla 浏览器
obj = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE浏览器
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
return obj;
}
//当输入框的内容变化时,调用该函数
function searchSuggest() {
var inputField = document.getElementById("txtSearch");
var suggestText = document.getElementById("search_suggest");
if (inputField.value.length > 0) {
var o=createXMLHttpRequest();
var url = "Server.aspx?searchText=" + escape(inputField.value);
o.open("GET", url, true);
o.onreadystatechange = function(){
if(o.readyState == 4){
if(o.status == 200){
var sourceText = o.responseText.split("\n");
if(sourceText.length>1){
suggestText.style.display="";
suggestText.innerHTML = "";
for(var i=0;i<sourceText.length-1;i++) {
var s='<div onmouseover="javascript:suggestOver(this);"';
s+=' onmouseout="javascript:suggestOut(this);" ';
s+=' onclick="javascript:setSearch(this.innerHTML);" ';
s+=' class="suggest_link">' +sourceText[i]+'</div>';
suggestText.innerHTML += s;
}
}
else{
suggestText.style.display="none";
}
}
}
};//指定响应函数
o.send(null); // 发送请求
}
else {
suggestText.style.display="none";
}
}
function suggestOver(div_value){
div_value.className = "suggest_link_over";
}
function suggestOut(div_value){
div_value.className = "suggest_link";
}
function setSearch(obj){
document.getElementById("txtSearch").value = obj;
var div = document.getElementById("search_suggest");
div.innerHTML = "";
div.style.display="none";
}
function tbblur(){
var div = document.getElementById("search_suggest");
//div.innerHTML = "";
div.style.display="none";
}
</script>
<style type="text/css" media="screen">
body
{
font: 11px arial;
}
.suggest_link
{
background-color: #FFFFFF;
padding: 2px 6px 2px 6px;
}
.suggest_link_over
{
background-color: #E8F2FE;
padding: 2px 6px 2px 6px;
}
#search_suggest
{
position: absolute;
background-color: #FFFFFF;
text-align: left;
border: 1px solid #000000;
}
/*input*/
.input_on{
padding:2px 8px 0pt 3px;
height:18px;
border:1px solid #999;
background-color:#FFFFCC;
}
.input_off{
padding:2px 8px 0pt 3px;
height:18px;
border:1px solid #CCC;
background-color:#FFF;
}
.input_move{
padding:2px 8px 0pt 3px;
height:18px;
border:1px solid #999;
background-color:#FFFFCC;
}
.input_out{
/*height:16px;默认高度*/
padding:2px 8px 0pt 3px;
height:18px;
border:1px solid #CCC;
background-color:#FFF;
}
</style>
</head>
<body>
<form id="form1" action="">
<input type="text" id="txtSearch" name="txtSearch" onkeyup="searchSuggest();" size="20" class="input_out" onfocus="this.className='input_on';this.onmouseout=''" onblur="this.className='input_off';this.onmouseout=function(){this.className='input_out'};" onmousemove="this.className='input_move'" onmouseout="this.className='input_out'" /><br />
<div id="search_suggest" style="display:none"></div>
<p>welcome to <a href="http://hi.baidu.com/mypc007">小虫的空间</a></p>
</form>
</body>
</html>
2.1,Server.aspx(数据提供页,此页面中删除其它多余代码,只留最上面一行。如果这里改了名请记得显示页面的调用处也要改哈-_-)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Server.aspx.cs" Inherits="Server" %>
2.2,Server.aspx.cs(数据提供页CS代码)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Data.SqlClient;
public partial class Server : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["searchText"] != null)
{
if (Request.QueryString["searchText"].ToString().Trim().Length > 0)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection("Server=mypc007;DataBase=sql2005_test1;User Id=sa;pwd=123"))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = string.Format(
"Select distinct top 10 country From iptable Where country like '{0}%'",
Request.QueryString["searchText"]);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
conn.Open();
adapter.Fill(dt);
}
string returnText = "";
if (dt != null && dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
returnText += dt.Rows[i][0].ToString() + "\n";
}
}
Response.Write(returnText);
}
}
}
}