王留军

 

jquery autocomplete 自动完成

支持ie,firefox,chrome等浏览器

head添加引用

<link rel="stylesheet" type="text/css" href="http://www.cnblogs.com/CSS/jquery.autocomplete.css" />
   
    <script type="text/javascript" src="http://www.cnblogs.com/JS/jquery-1.4.min.js"></script>
    <script type="text/javascript" src="http://www.cnblogs.com/JS/jquery.autocomplete.js"></script>
    <script type="text/javascript" >
        jQuery(function () {       
        jQuery("#txtCustomizedField").autocomplete('AutoComplete.aspx', {
                httpMethod: "POST", //使用POST调用WebService
                dataType: 'xml', //返回数据类型为XML
                minchar: 0, //最小响应字符数量
                selectFirst: false, //默认不选中第1条
                //格式化选项,由于WebService返回的数据是JSON格式,现在要转成HTML以TABLE形式显示
                formatItem: function(row, i, max) {
                    var obj = eval("(" + row + ")"); //将JSON转换成对象
                    var item = "<table id='auto" + i + "' style='width:100%;'> <tr><td align='left'>" +
                        obj.value + "</td> </tr> </table>"; //<td align='right' style='color:green;'>"+obj.num+"</td>
                    return item;
                },
                //格式化结果,当选中时返回具体的值
                formatResult: function (row, i, max) {
                    var obj = eval("(" + row + ")");
                    return obj.value;
                }
            });
        });
    </script>  

 

取数据AutoComplete.aspx前台代码只需要一句:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoComplete.aspx.cs" Inherits="GDC.CQMS.Web.UserControlsV4.PreCQ.AutoComplete" %>

后台代码:

 protected void Page_Load(object sender, EventArgs e)
        {
            string q = Request["q"].ToString();
            //List<string> list = new List<string>();
            string rlt = string.Empty;
            DataTable dt = prjsrv.GetCustomizedField(q);
            Response.Clear();
            Response.Charset = "UTF-8";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/xml";
            Response.Write("<?xml version='1.0' encoding='utf-8'?>");
            Response.Write("<ArrayOfString xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='http://tempuri.org/'>");
            string template = "{{value:'{0}',n:'{1}'}}" + System.Environment.NewLine;//+”\n”
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    rlt = "<string>" + string.Format(template, dr["CustomizedField"].ToString(), "n") + "</string>";
                    Response.Write(rlt);  
                }
            }

            Response.Write("</ArrayOfString>");  
            Response.Flush();
            Response.End();
        }

posted on 2012-11-09 11:18  王留军  阅读(168)  评论(0编辑  收藏  举报

导航