随笔 - 290  文章 - 10  评论 - 83  2

下载Prototype,和 Ajax Autocomplete for Prototype 2个js文件

/*
 *
 *  Ajax Autocomplete for Prototype, version 1.0.3
 *  For details, see the web site: http://www.devbridge.com/projects/autocomplete/
 *
 */

下面用一个例子说明: 用户在textbox输入员工编号,就会出現员工编号,姓名的autocomplete

<asp:TextBox ID="txtEmployeeNum" runat="server" MaxLength="50"  TabIndex="12"
 Width="130px"></asp:TextBox>    
<script type="text/javascript">
  new Autocomplete('txtEmployeeNum', { serviceUrl:'../service/Employee.ashx'
         onSelect: function(value, data){
        $("txtEmployeeNum").value= data;
        var arr = value.split(" ");
        $("txtEmployeeName").value = arr[0];  
      }
 });
</script> 

 

Ajax 需要从后台拿到数据庫员工的数据,后台页面就是Employee.ashx.

ashx会只生成所需的数据,而没有多余的html

 

 

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Employee : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

    //用户在textbox输入的字符,在Request["query"]里
            string query = context.Request["query"];
            EmployeeParas paras = new EmployeeParas();
            paras.employeeNum = query;
            paras.employeeName = query;

            EmployeeHandler eh = new EmployeeHandler();
            List<Employee> Emplist = eh.LoadEmployeeByParasForAJAX(paras);

            string JSON = string.Empty;
            JSON = "{ query:'" + query + "',suggestions:[";
            if (Emplist.Count > 0)
            {
                foreach (Employee item in Emplist)
                {
                    JSON += "'" + item.employeeName + "      " + item.employeeNum + "',";
                }
                //del last commar
                JSON = JSON.Substring(0, JSON.Length - 1);

            }

            JSON += "],data:[";
            if (Emplist.Count > 0)
            {
                foreach (Employee item in Emplist)
                {
                    JSON += "'" + item.employeeNum + "',";
                }
                //del last commar
                JSON = JSON.Substring(0, JSON.Length - 1);
            }
            JSON += "]}";
            context.Response.Write(JSON);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

 

 

posted on 2009-11-12 10:26  Gu  阅读(...)  评论(... 编辑 收藏