搜索建议(Searching Suggestion),已布置好样式

大家应该都看到过 GOOGLE 的搜索建议,就是当我们在输入关键词时,GOOGLE 会根据我们目前已输入的字显示相关的关键字建议,这就是搜索建议,现在很多网站都实现该友好的功能,如 YAHOO、狗狗搜索等。

实现该功能的思路就是:
  1. 在关键字输入框里,当用户按键弹起时,发送输入框里的字符串到服务器。
  2. 服务器根据收到客户端发来的字进入匹配搜索
  3. 将匹配用户已输入字的记录回发到客户端
  4. 客户端收到服务端的响应,输出建议。

其实就是异步回发(AJAX)。

下面是一个实例,实例实现的是搜索 SQL Server 默认数据库 Northwind 表 Customers 字段 CustomerID,当用户要输入框输入字时,返回该字段值与用户输入的字开头匹配的记录,即 CustomerID LIKE '用户已输入的字%'。

样式已设置好,显示建议的行为绝对位置,所以该行不会显示网页上的内容。

文件名:WordSuggest.aspx

源码如下:

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

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  runat ="server" >
    
< title > 无标题页 title >
    
< style  type ="text/css" >
    .CInput
{ border : solid 1px gray ; width : 300px }
    #divSuggestions
{ border : solid 1px gray ; width : 300px ; background : #fff ; visibility : hidden }
    #divSuggestions span
{ display : block ; padding : 3px }
    
style >
head >
< body >
    
< form  id ="form1"  runat ="server" >
    
< div >
    
< h1 > 搜索建议 DEMO h1 >
    
< span > http://www.code-studio.net  span >
    
< hr  />
    
< table  style ="border-collapse:collapse;" >< tr >< td >< asp:TextBox  ID ="txtInput"  runat ="server"  CssClass ="CInput"  onkeyup ="sendRqt(this)" > asp:TextBox >
    
< asp:Button  ID ="Button1"  runat ="server"  Text ="Submit"   /> td > tr >
    
< tr  style ="position:absolute;" >< td >< div  id ="divSuggestions" > div > td > tr > table >
    
div >
    
form >
    
< script  type ="text/javascript" >
    
var  xhr;
    
var  isIe = window.navigator.appName.indexOf( " Netscape " ==   - 1 ? true : false ;

    
function  $(sElmId){ return  document.getElementById(sElmId);}
    
function  crtRqt(){
        
if (window.ActiveXobject)
            xhr
= new  ActiveXObject( " Microsoft.XMLHTTP " );
        
else  xhr = new  XMLHttpRequest();
    }
    
function  sendRqt(srcElm){
        
var  sInput = srcElm.value;
        
if (sInput != "" ){
            
var  url = " wordsuggest.aspx?t= " + new  Date().getTime() + " &w= " + sInput;
            crtRqt();
            xhr.onreadystatechange
= hdlRsp;
            xhr.open(
" GET " ,url, true );
            xhr.send(
null );
        }
        
else  $( " divSuggestions " ).style.visibility = " hidden " ;
    }
    
function  hdlRsp(){
        
if (xhr.readyState == 4 && xhr.status == 200 ){
            
var  rspText = xhr.responseText;
            
var  oDiv = $( " divSuggestions " );
            
if (rspText != "" ){
                
var  arrRspText = xhr.responseText.split( ' , ' );
                
var  sInnerHtml = "" ;
                
for ( var  i = 0 ;i < arrRspText.length; ++ i){
                    sInnerHtml
+= " "
                                
+ "  οnclick='setInput(this)'> " + arrRspText[i] + "
" ;
                }
                oDiv.innerHTML
= sInnerHtml;
                oDiv.style.visibility
= " visible " ;
            }
            
else  oDiv.style.visibility = " hidden " ;
        }
    }
    
function  setStyle(srcElm,bOver){
        srcElm.style.background
= bOver ? " orange " : "" ;
    }
    
function  setInput(srcElm){
        $(
" <%=txtInput.ClientID %> " ).value = srcElm.innerHTML;
    }
    
script >
body >
html >

.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  WordSuggest : System.Web.UI.Page
{
    
protected   void  Page_Load( object  sender, EventArgs e)
    {
        
string  strInput  =   string .IsNullOrEmpty(Request.QueryString[ " w " ])  ?   string .Empty : Request.QueryString[ " w " ];
        
if  (strInput.Trim().Length  !=   0 )
        {
            Suggeste(strInput);
        }
    }

    
private   void  Suggeste( string  originalStr)
    {
     
/*  搜索建议
      * 文件名: WordSuggest.aspx
      * 功能描述: 根据用户输入,在数据库 Northwind 的表 Customers 查找 CustomerID 字段值匹配的记录.
      
*/
        SqlConnection conn 
=   new  SqlConnection( " data source=localhost;database=northwind;user id=sa;password=你的密码 " );
        
string  cmdText  =   " SELECT TOP 10 CustomerID FROM Customers WHERE CustomerID LIKE @w " ;
        SqlParameter para 
=   new  SqlParameter( " @w " string .Format( " {0}% " , originalStr));
        SqlCommand cmd 
=   new  SqlCommand();
        cmd.Connection 
=  conn;
        cmd.CommandText 
=  cmdText;
        cmd.Parameters.Add(para);
        conn.Open();
        SqlDataReader reader 
=  cmd.ExecuteReader();
        System.Text.StringBuilder sb 
=   new  System.Text.StringBuilder();
        
while  (reader.Read())
        {
            sb.AppendFormat(
" {0}, " , reader[ 0 ]);
        }
        reader.Close();
        conn.Close();
        Response.ContentType 
=   " text/plain " ;
        Response.Clear();
        
if  (sb.Length  !=   0 )
        {
            Response.Write(sb.ToString().Remove(sb.Length 
-   1 ));
        }
        
else
        {
            Response.Write(
string .Empty);
        }
        Response.Flush();
        Response.Close();
    }
}

你可能感兴趣的:(搜索建议(Searching Suggestion),已布置好样式)