实现textbox输入时模糊查询

1。引用的一个文件

代码
//  JScript 文件

// ********************************************************
// 创建日期:  2010-05-5
// 內容说明:  自动完成JS类
// 用法:
//  onkeyup = "findNames('id1','id2','1');" id1 - 自动完成文本框id,id2 - 赋值文本框id  1- 表示 id1字段模糊查询,2-  'id2字段模糊查询
//  onblur = "lostfocus(this);"
// ********************************************************
  
  var  inputField;        
// 输入文本框
  var  outputField;        // 输出文本框
  var  DivResult ;         // div
  var  xmlHttp;            // XMLHttpRequest 
  var  fontsize  =   2 ;       // 字体大小
  var  flagValue ;         // 标示符(1 - 以code 检索,2 以name 检索)
  var  selectName   =   "" ;   // 鼠标选中单元格name值
  var  selectValue  =   "" ;   // 鼠标选中单元格code值
  
// 未选中颜色
  var  NobackColor  =   " #FFFFFF "
  var  NoColor 
=   " #000000 " ;
  
// 选中颜色
  var backColor  =   " #3161CE " ;
  var sColor 
=   " #FFFFFF " ;

    function findNames(inputName,outputName,flag)
// 键盘出发事件
    {
        inputField  
=  document.getElementById(inputName);
        outputField 
=  document.getElementById(outputName);
        flagValue 
=  flag;
        
// code 文本框不能用是,禁用自动填充
         if (outputField.disabled  ==   true )
        {
          
return  ;
        }
        
// 创建DIV
        if (DivResult  ==   null || typeof (DivResult) == " undefined " )
       {
             DivResult 
=  document.createElement( " div " );
             DivResult.setAttribute(
" id " , " divid " );
             DivResult.style.cursor   
=     " default " ; //  设置光标  
             DivResult.onblur  =  function(){ lostfocus( this )}
             
             var parent 
=   inputField.parentElement;
             
if ( typeof (parent) != " undefined " )
             {
                parent.appendChild(DivResult);
             }
       }
       
// 如果按下 向上, 向下 或 回车
         if  ( event .keyCode  ==   38   ||   event .keyCode  ==   40   ||   event .keyCode  ==   13 )
        { 
           
return ;
        } 
        
else   if  (trim(inputField.value)  ==   "" )
        {
            
// 初始化div
           InitItem();
           
return ;
        }
        
else
        {
            
if (window.XMLHttpRequest)
            {
                xmlHttp 
=   new  XMLHttpRequest();
                
if (xmlHttp.overrideMimeType)
                   xmlHttp.overrideMimeType(
" text/xml " );
            }
            
else   if (window.ActiveXObject)
            {
                
try
                {
                    xmlHttp 
=   new  ActiveXObject( " Msxml2.XMLHTTP " );
                }
                
catch (e)
                {
                    xmlHttp 
=   new  ActiveXObject( " Microsoft.XMLHTTP " );
                }
            }

            
if (xmlHttp  ==   null )
                
return ;
            
            xmlHttp.onreadystatechange 
=  ShowResult; // 设置回调函数
            xmlHttp.open( " GET " " AutoComplete.aspx?flag= " +  escape(flagValue) + " &InputValue= "   +  escape(trim(inputField.value)).replace( ' + ' , ' %2B ' ),  true ); // 编码不一致
            xmlHttp.send( null ); 
        }
    }
    
    function ShowResult() 
// 回调函数
    {
       
if  (xmlHttp.readyState  ==   4 ) // 请求完成
       {
          
if (xmlHttp.status  ==   200 ) // 交易成功
          {
              
// 获取xml数组
              var values  =  xmlHttp.responseXML.getElementsByTagName( " ProductName " );   
              var ids  
=  xmlHttp.responseXML.getElementsByTagName( " ProductCode " );    
              var size 
=  values.length; 
              InitItem();
// 初始化div
               if (size  == 0 )
              {
                
return ;
              }
              
// 设置Div位置
              setDiv(size)
              tbl 
=  document.createElement( " table " );
              tbl.setAttribute(
" id " , " AutoComplete_tbl " ); // 设置表id
              tbl.setAttribute( " cellSpacing " , " 1 " );
              tbl.setAttribute(
" cellPadding " , " 1 " );
                      
              tbody 
=  document.createElement( " tbody " );
             
              var row, cell, txtNode;   
              
for  (var i  =   0 ; i  <  size; i ++ ) {      // 开始填充    
                  if (values[i].firstChild  ==   null )
                 {
                     var nextNode 
=   ''
                 }
                 
else
                 {
                   var nextNode 
=  values[i].firstChild.data;   
                 }
                 
if (ids[i].firstChild  ==   null )
                 {
                     var nextId 
=   ''
                 }
                 
else
                 {
                   var nextId 
=  ids[i].firstChild.data; 
                 }
                 row 
=  document.createElement( " tr " );  
                 row.setAttribute(
" ReturnValue " ,nextId) 
                 row.setAttribute(
" ReturnName " ,nextNode);
                 row.onmouseover 
=  function(){ mouseover( this );}
                 row.onmouseout  
=  function(){ mouseout( this );}
                 row.setAttribute(
" id " ,i); // 行数标示符 
             
                 cell 
=  document.createElement( " td " );
                 cell.setAttribute(
" bgcolor " " #FFFAFA " );   
                 cell.setAttribute(
" border " " 0 " ); 
               
//   cell.setAttribute("nowrap","true"); // 不自动换行
                
                 font 
=  document.createElement( " font " ); 
                 font.setAttribute(
" size " ,fontsize + " px " );
                 
if (flagValue  ==   " 1 " )
                 {
                    txtNode 
=  document.createTextNode(nextId  + "  /  "   +  nextNode); 
                 }
                 
else   if (flagValue == " 2 " )
                 {
                    txtNode 
=  document.createTextNode(nextNode  + "  /  "   +  nextId); 
                 }
                 
                 font.appendChild(txtNode);
                 cell.appendChild(font) ;
                 row.appendChild(cell);
                 tbody.appendChild(row);
              } 
              tbl.appendChild(tbody)
              DivResult.appendChild(tbl);
              
// 显示属性
              DivResult.style.display  =   ""
           }
          
else   if  (xmlHttp.status  ==   204 ) // 请求收到,但返回信息为空
          {
             InitItem();
// 初始化div
          }
        }
     }     
 
   function  InitItem()
// 初始化Div
    {
        
if (DivResult  !=   null && typeof (DivResult) != " undefined " )
        {
           DivResult.style.display 
=   ' none ' ;
           DivResult.innerHTML 
=   "" ;
        }
        selectValue 
=   "" ;
        selectName 
=   "" ;
        currentIndex 
=   - 1 ;
    }

   
    
// 设置页面值
    function ReturnAutoComplete(ReturnValue,ReturnName)
    {
      
if (flagValue  ==   " 1 " )
      {
          
// 页面元素赋值
          inputField.value  =  ReturnValue;
          outputField.value 
=  ReturnName; 
      }
      
else   if  (flagValue  ==   " 2 " )
      {
          inputField.value 
=  ReturnName;
          outputField.value 
=  ReturnValue; 
      }
    }
  function mouseover(obj)
  {
      
// 选中颜色
      obj.style.backgroundColor  =  backColor; 
      obj.style.color 
=  sColor;
      selectValue 
=  obj.ReturnValue;
      selectName 
=  obj.ReturnName;
  }
  
  function mouseout(obj)
// 鼠标离开事件
  {
     
// 设置默认颜色
      obj.style.backgroundColor  =  NobackColor; 
      obj.style.color 
=  NoColor;
      selectValue 
=   "" ;
      selectName 
=   "" ;
  }
 function setDiv(rowSize)
// 设置div位置
 {
    DivResult.style.position 
=   " absolute " ;
    DivResult.style.border 
=   " 1px solid black " ;
    DivResult.style.top  
=  inputField.getBoundingClientRect().bottom  - 2   +   " px " ;
    DivResult.style.left 
=  inputField.getBoundingClientRect().left  -   2   +   " px " ;
    DivResult.style.backgroundColor 
=  NobackColor;
    
    
if (rowSize  >   12 ) // 设置滚动条    add 2009-6-16 on xuzhenzhong
    {
       DivResult.scrollTop 
=   " 0 " // 滚动条位置初始化 add 2009-6-16 on xuzhenzhong
       DivResult.scrollLeft  =   " 0 " ;
       DivResult.style.height 
=   " 204px " ;
       DivResult.style.overflow 
=   " auto " ;
    }
    
else
    {
       DivResult.style.overflow 
=   " hidden " ; // 取消滚动条
       DivResult.style.height  =   "" ;
    }
 }
 
 
// 输入文本框失去焦点
 function lostfocus(ob)
 {
   
if ((ob  ==  inputField || ob.id  ==   ' divid ' ) && (selectValue  !=   "" ))
   {
      ReturnAutoComplete(selectValue,selectName);
      InitItem();
   }
   
if (document.activeElement.id  !=   ' divid ' )
   {
      InitItem();
   }
 }
 
 
// 删除左右两端的空格
function trim(str)
{
   
return  str.replace( / ( ^ /s * ) | (/s * $) / g, '' );
}



 



 

2。js牵涉到的一个AutoComplete.aspx页面内容

代码
public   partial   class  AutoComplete : System.Web.UI.Page
{
    CommBO bo 
=   new  CommBO();
    
string  flag  =   string .Empty; //  标示符
     string  InputValue  =   string .Empty; // 输入值
     string  ReturnStr  =   string .Empty; // xml

    
//  页面加载事件
     protected   void  Page_Load( object  sender, EventArgs e)
    {
        
try
        {
            flag 
=  Request.QueryString[ " flag " ??   "" ; // 查询条件标示符
            InputValue  =  Request.QueryString[ " InputValue " ]; // 输入值
            AutoCompletXML(); // 填充xml
            HttpContext.Current.Response.ContentType  =   " text/xml " ;
            HttpContext.Current.Response.Charset 
=   " GB2312 " ;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
// 禁用本地缓存
            HttpContext.Current.Response.Cache.SetNoStore();
            HttpContext.Current.Response.ContentEncoding 
=  System.Text.Encoding.GetEncoding( " UTF-8 " );
            HttpContext.Current.Response.Write( ReturnStr);
            HttpContext.Current.Response.End();
        }
        
catch
        { ; }
    }
    
//  填充xml
     private   void  AutoCompletXML()
    {
        
try
        {
            Dictionary
< string object >  dict  =   new  Dictionary < string object > ();
            DataSet ds 
=   new  DataSet();
            
int  intRowCount  =   10 ; // 默认自动完成显示最大行数
            intRowCount  =  Convert.ToInt32(ConfigurationManager.AppSettings[ " AutoCompleteRowCount " ].Trim());
            
if  (flag.Equals( " 1 " ))
            {
                dict.Add(
" @ "   +  ConstMessage.TABLE_FIELD_NAME.Product.PRODUCTCODE , " % "   +  InputValue  + " % " );
            }
            
else   if  (flag.Equals( " 2 " ))
            {
                dict.Add(
" @ "   +  ConstMessage.TABLE_FIELD_NAME.Product.PRODUCTNAME , " % " +  InputValue  + " % " );
            }
            
else
            {
                
return ;
            }
            
// 执行数据库操作
            ds  =  bo.GetByProduct(dict,intRowCount);
            ReturnStr 
=  ds.GetXml(); // 生成xml
        }
        
catch
        {
            ReturnStr 
=   string .Empty;
        }

    }
}

 

3。使用页面,对应的页面控件

----添加js引用

----页面添加控件

<div>
        <asp:TextBox ID="txtProductCode" runat="server" CssClass="text_Mandatory" MaxLength="25"
            AutoCompleteType="Disabled"></asp:TextBox>
        <asp:TextBox ID="txtProductName" runat="server" CssClass="text_ProductName" MaxLength="30"
            AutoCompleteType="Disabled"></asp:TextBox>
    </div>

---cs中为txtbox添加js事件

 this.txtProductCode.Attributes.Add("onkeyup", "findNames('" + this.txtProductCode.ClientID + "','" + this.txtProductName.ClientID + "','1');");
        this.txtProductName.Attributes.Add("onkeyup", "findNames('" + this.txtProductName.ClientID + "','" + this.txtProductCode.ClientID + "','2');");
        this.txtProductCode.Attributes.Add("onblur", "lostfocus(this);");
        this.txtProductName.Attributes.Add("onblur", "lostfocus(this);");

4。数据库调用层根据编码或名称的模糊查询略

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过在 ASP.NET 中使用 Ajax 实现模糊查询。具体步骤如下: 1. 在 ASP.NET 页面上添加一个文本框和一个控件容器(例如 DIV)用于显示查询结果。 2. 在页面的头部引入 jQuery 库和 Ajax 库。 ```html <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> ``` 3. 在文本框上添加一个事件,在用户输入内容触发 Ajax 请求。 ```html <asp:TextBox ID="txtSearch" runat="server" onkeyup="search();" /> <div id="searchResults"></div> ``` 4. 在 JavaScript 中编写一个函数来处理 Ajax 请求,并将查询结果显示在控件容器中。 ```javascript function search() { var query = $('#txtSearch').val(); if (query.length > 2) { // 只有当输入字符大于2才进行查询 $.ajax({ type: 'POST', url: 'Search.aspx/GetResults', // 后台处理 Ajax 请求的页面 data: '{query: "' + query + '" }', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (response) { var results = response.d; var html = ''; for (var i = 0; i < results.length; i++) { html += '<div>' + results[i] + '</div>'; } $('#searchResults').html(html); } }); } else { $('#searchResults').html(''); // 清空查询结果 } } ``` 5. 在后台编写一个 WebMethod 来处理 Ajax 请求并返回查询结果。 ```c# using System.Web.Services; [WebMethod] public static List<string> GetResults(string query) { // 在这里编写查询逻辑,返回一个包含查询结果的 List<string> } ``` 通过以上步骤,就可以实现在 ASP.NET 中使用 Ajax 进行文本框模糊查询了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值