实现类似google搜索效果,文本框输入智能提示,(经过改进 支持多个文本框的效果)

来源:互联网 发布:ipad air2蜂窝数据 编辑:程序博客网 时间:2024/05/16 16:20

主页面前台代码:(AjaxTest.aspx)    注:AjaxTest.aspx.cs后台不用写任何代码

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxTest.aspx.cs" Inherits="AjaxTest" %>

<!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>ajax智能提示</title>
    <style type="text/css">
        html, body
        {
            width: 100%;
            height: 100%;
        }
        ul
        {
            padding: 0px;
            margin: 0px;
            list-style: none;
        }
        li
        {
            cursor: pointer;
            padding: 0px 5px;
            line-height: 25px;
            height: 25px;
        }
    </style>
</head>
<body>
    测试1(有效果):
    <input type='text' id='txtInput' onkeyup='callServer(this.id)' />
    <div id='divShow' style="position: absolute; z-index: 9999; width: 200px; height: auto;
        display: none; border: 1px solid #ddd">
    </div>
    &nbsp;&nbsp;&nbsp;&nbsp; 测试2(无效果):
    <input type='text' id='txtInput2' />
    &nbsp;&nbsp;&nbsp;&nbsp; 测试3:(有效果)
    <input type='text' id='txtInput3' onkeyup='callServer(this.id)' />
</body>

<script type="text/javascript">
 var xmlHttp=false;
    try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e2)
      {
      xmlHttp=false;
      }
    }
    if(!xmlHttp && typeof XMLHttpRequest!='undefined')
    {
    xmlHttp=new XMLHttpRequest();
    }
   
    var txtInput ;
    var divShow ;
    function callServer(id)
    {
    Init(id); 
    var url="Test.aspx?txtinput="+escape(txtInput.value);
    xmlHttp.open("get",url,true);  //建立新请求
    xmlHttp.onreadystatechange=updatePage;  //指定回调方法
    xmlHttp.send(null);
    }
   
    var keys=new Array(); 
    function updatePage()
    {
  
      if(xmlHttp.readyState==4)
       {
         if(xmlHttp.status==200)
         {
          keys= xmlHttp.responseText.split(','); //ajax返回的数据
          getSearchKeys();
         }
      }
    }


function Init(id)
{
     txtInput =document.getElementById(id);
     divShow = document.getElementById("divShow");
     var p =getAbsPoint(txtInput);
     divShow.style.left = p.x +'px';
     divShow.style.top = p.y + txtInput.offsetHeight + 'px';
     txtInput.onclick = divShow.onclick=function(e)
     {
         e = e||event;
         var t = e.target||e.srcElement

        if(t.tagName.toLowerCase()=='li')
        {
          txtInput.value = t.innerHTML;
           divShow.style.display = "none";
           return;
        }
        if(e && e.stopPropagation){
          //W3C取消冒泡事件
          e.stopPropagation();
          }else{
          //IE取消冒泡事件
          window.event.cancelBubble = true;
          }
    };
    document.body.onclick=function(e)
    {
        divShow.style.display = "none";
    };
};
function getSearchKeys()
{
 
  var s= txtInput.value;
    if(s=='')
    {
        divShow.style.display = "none";
        return;
    }
      var arr=['<ul>'];
      for(var i=0;i<keys.length;i++)
      {
        if(keys[i].indexOf(s)>=0){
        arr.push('<li>'+keys[i]+'</li>');
       }
      }
   
      if(arr.length>1){
        arr.push('</ul>');
        divShow.innerHTML = arr.join('');
        divShow.style.display = "block";
      }else{
        divShow.style.display = "none";
      }
}

function getAbsPoint(e)
{
    var x = e.offsetLeft;
    var y = e.offsetTop;
    while(e = e.offsetParent)
    {
        x += e.offsetLeft;
        y += e.offsetTop;
    }
    return {"x": x, "y": y};
}
</script>

</html>

Test.aspx的前台代码(就一行而已)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

 

Test.aspx后台代码:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data.OleDb;

public partial class Test : System.Web.UI.Page
{

    public string tip = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = string.Empty;
        string input = Request.QueryString["txtinput"];
        List<string> list = GetCLCAll(input);
        List<string> listNew = new List<string>();
        foreach (string item in list)
        {
            if (!listNew.Contains(item))  //去掉重复数据
            {
                listNew.Add(item);
            }
        }
        foreach (string item in listNew)
        {
            str += item + ",";
        }
        if (str.Length != 0)
        {
            str = str.Substring(0, str.Length - 1);//去掉最后一个逗号
        }
        tip = str;
        Response.Write(tip);
    }

    public List<string> GetCLCAll(string input)
    {
        List<string> list = new List<string>();
        string sql = "select top 10 * from testTable where name like '%" + input + "%'";
        string ACCESS_CONN_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
            + " D://AJAX测试//test.mdb ;User Id=admin;Password=;";
        try
        {
            using (OleDbConnection access_conn = new OleDbConnection(ACCESS_CONN_STRING))
            {
                OleDbCommand access_cmd = new OleDbCommand(sql, access_conn);
                access_conn.Open();
                OleDbDataAdapter da = new OleDbDataAdapter(access_cmd);
                DataTable table = new DataTable();
                da.Fill(table);
                foreach (DataRow row in table.Rows)
                {
                    list.Add((string)row["name"]);
                }
                access_conn.Close();
            }
        }
        catch (Exception)
        {
            throw;
        }
        return list;
    }
}

原创粉丝点击