Jquery自动完成功能
前端页面代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jquery自动完成.aspx.cs" Inherits="jquery自动完成" %> <!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"> <script src="javsscript/jquery-1.7.1.js" type="text/javascript"></script> <style type="text/css"> .listbox { position: relative; left: 20px; margin: 10px; margin-top:-2px; margin-left:70px; width: 149px; height:112px; background-color:White; color: #000; border: 2px solid Gray; overflow:auto; } .nameslist { margin: 0px; padding: 0px; list-style: none; } .hover { background-color: #E2EAFF; color: Blue; margin-bottom:0px; } </style> <script type="text/javascript"> $(document).ready(function() { $('.listbox').hide(); $('.userid').keyup(function() { var data = $('.userid').val(); if (data.length < 1) {//是否有输入值 return; } $.ajax ({ type: "post", contentType: "application/json;utf-8", url: "IbeaconWebService.asmx/GetUsers", data: "{userid:'" + data + "'}", datatype: "json", success: function(usersname) { /*方法一当后台返回序列号字符串数组时 var obj = $.parseJSON(usersname.d); for (var i = 0; i < obj.length; i++) { alert(obj[i].UserName); } */ var obj = eval(usersname.d); $('.nameslist').empty(); //清空已有的数据 if (obj.length < 1) { //没有数据则隐藏展示层 $('.listbox').hide(); return; } for (var i = 0; i < obj.length; i++) //循环返回的数据 { $('.listbox').show(); var li = $('<li>' + obj[i].name + '</li>');//获得li对象 $('.nameslist').prepend(li); //向ul添加li对象 $('li').hover(function() //设置li的鼠标移入移出事件并设置样式 { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); }); $('li').click(function() //点击li给文本框赋值 { $('.userid').val($(this).text()); $('.listbox').hide(); });
//当鼠标点击页面时隐藏展示div
$(document).click(function(){
$('.listbox').hide();
}); } } }); });
}); </script> <title>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> <span class="label">UserName:</span> <input type="text" name="username" class="userid" autocomplete="off" style="border:solid 1px Gray;"> <div class="listbox"> <ul class="nameslist"> </ul> </div> </div> </form> </body> </html>
后台webservice代码:
using System; using System.Collections; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; using DBHelper; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Text; using System.Web.Script.Serialization; using System.Collections; using System.Collections.Generic; /// <summary> ///IbeaconWebService 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 [System.Web.Script.Services.ScriptService] public class IbeaconWebService : System.Web.Services.WebService { public IbeaconWebService() { //如果使用设计的组件,请取消注释以下行 //InitializeComponent(); } [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public string GetUsers(string userid) { string username = userid; string users = string.Empty; string ConnectionString = SqlHelper.GetConnectionString(); SqlParameter[] par = new SqlParameter[]{ new SqlParameter("@userid",username) }; DataSet ds = new DataSet(); ds = SqlHelper.ExecuteDataSet(ConnectionString, CommandType.StoredProcedure, "proc_getnamesbyuserid", par); ///方法一返回序列化的字符串数组 //JavaScriptSerializer js = new JavaScriptSerializer(); // IList<User> al = new List<User>(); //for (int i = 0; i < ds.Tables[0].Rows.Count;i++ ) { //al.Add(new User() {UserName=ds.Tables[0].Rows[i]["username"].ToString()}); //sb.Append(); //} // users = js.Serialize(al); //return users ///方法二返回字符串数组 StringBuilder sb = new StringBuilder(); sb.Append("["); if (ds.Tables[0].Rows.Count < 1) { sb.Append("]"); return sb.ToString(); } foreach (DataRow item in ds.Tables[0].Rows) { string str = item["username"] as string; sb.Append("{name:'" + str + "'},"); } sb.Remove(sb.Length - 1, 1); sb.Append("]"); return sb.ToString(); } } public class User { public string UserName { get; set; } }
存储过程代码:
USE [test] GO /****** Object: StoredProcedure [db_accessadmin].[proc_getnamesbyuserid] Script Date: 05/10/2012 16:10:36 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER proc [db_accessadmin].[proc_getnamesbyuserid] @userid varchar(30) as declare @sql varchar(400) set @sql='select * from dbo.users where username like ''\'+@userid+'%'' ESCAPE ''\''' --ESCAPE '\'转义,即当@userid=%时不会查出所有用户 exec(@sql)
效果图: