注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

伯纳乌の夢

可以挽回么?我们按“ Ctrl+Z”撤销掉吧。对不起啦~~

 
 
 

日志

 
 
 
 

jQuery autocomplete示例  

2013-12-23 14:21:43|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
1) 最简单的示例, 抓取数组

前台页面:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="testAutoComplete.aspx.cs"
    Inherits="HRMS.testAutoComplete" %>

<!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>
    <link href="JavaScript/jquery-ui-1.10.3.custom.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
        month:<asp:TextBox ID="txtMonth" runat="server"></asp:TextBox>
        <br />
        dept:
        <asp:DropDownList ID="ddlDept" runat="server">
        </asp:DropDownList>
        <br />
        <br />
        <asp:DropDownList ID="ddlSector" runat="server">
        </asp:DropDownList>
    </div>
    </form>
    <script src="JavaScript/jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="JavaScript/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
            $("#txtMonth").autocomplete({ source: months });

            $("#ddlDept").change(function () {
                $.ajax({
                    url: 'Page.aspx',
                    type: 'post',
                    data: "token=dept",
                    dataType: 'html',
                    success: function (data) {
                        $("#ddlSector").empty();
                        for (var i = 0; i < data.split("\n").length; i++) {
                            var newOption = "<option value='" + data.split("\n")[i] + "'>" + $("#ddlDept").val() + data.split("\n")[i] + "</option>";
                            $("#ddlSector").append(newOption);
                        }
                    },
                    error: function () {
                        alert("Something went wrong!");
                    }
                })
                return false;
            });
        });
    </script>
</body>
</html>

 
后台页面:
 protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ddlDept.Items.Add("AAA");
                ddlDept.Items.Add("BBB");
                ddlDept.Items.Add("CCC");
                ddlDept.Items.Insert(0, "");
            }
        }
 
Page页面:
 

protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if ((Request["token"] ?? "") == "ajax")
                {
                    // 下面这些内从可以放在一个方法里,然后通过“token”标记去判断执行哪个方法。
                    Response.Write("我是直接请求aspx页面返回的文字!");
                    Response.End();
                }
                if((Request["token"] ?? "")=="dept")
                {
                    string aa = null;
                    aa = "Plus\nBrowser\n";
                    var tags = new[] { "ActionScript", "Scheme" };
                    aa+= String.Join("\n", tags.Select(x => String.Format("\"{0}\"", x)));
                    Response.Write(aa);
                    Response.End();
                }
            }
        }


2.動態抓取後台數據庫
jQuery autocomplete示例 - mgracy - 伯纳乌の夢
 2.1)前台頁面WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="autoComplete.WebForm1" %>

<!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>
    <link href="jquery.autocomplete.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:TextBox ID="txtEmpNo" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtAD" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    </div>
    <script src="jquery-1.8.3.min.js" type="text/javascript"></script>
    <script src="jquery.autocomplete.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#txtEmpNo").autocomplete("Handler1.ashx", {
                //                            max: 6, //列表里的条目数
                minChars: 1, //自动完成激活之前填入的最小字符
                width: 200, //提示的宽度,溢出隐藏
                scrollHeight: 300, //提示的高度,溢出显示滚动条
                matchContains: true, //包含匹配,就是data参数里的数据,是否只要包含文本框里的数据就显示
                autoFill: false, //自动填充
                dataType: 'json',
                parse: function (data) {
                    var rows = []
                    if (data == null) { return rows; }
                    for (var i = 0; i < data.Table1.length; i++) {
                        rows[i] = {
                            data: data.Table1[i].EMPNO + "," + data.Table1[i].DOMINOCOUNT + "," + data.Table1[i].NAME,
                            value: data.Table1[i].EMPNO + "," + data.Table1[i].DOMINOCOUNT + "," + data.Table1[i].NAME,
                            result: data.Table1[i].EMPNO
                        };
                    }
                    return rows;
                },
                formatItem: function (row, i, max) {
                    return row
                },
                formatMatch: function (row, i, max) {
                    return row
                },
                formatResult: function (row, i, max) {
                    return row
                }
            }).result(function (event, data, formatted) {
                var row = data.split(",");
                $("#txtName").val(row[2]);
                $("#txtAD").val(row[1]);
            });
        });
    </script>
    </form>
</body>
</html>


2.2)後台頁面Handler1.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Text;

namespace autoComplete
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class Handler1 : IHttpHandler
    {
        string connStrOracle = "Data Source=TestDB;Persist Security Info=True;User ID=APP;Password=APP;Pooling=true";
        public void ProcessRequest(HttpContext context)
        {
            //   context.Response.ContentType = "text/plain";
            string myParam = context.Request.QueryString["q"].ToString();
            DataSet ds = null;
            if (!string.IsNullOrEmpty(myParam))
            {
                //JsonResult jsonr = new JsonResult();
                //nhmistodoe = new Models.NHMISTODOEntities();
                //List<EMPLOYEE> emplist = nhmistodoe.EMPLOYEE.Where(p => p.DOMINOCOUNT.Contains(q)).ToList();
                //jsonr.Data = emplist.ToArray();
                //return Json(jsonr, JsonRequestBehavior.AllowGet);
                Class1 con = new Class1();
                string sql = "select emp_no EMPNO,name NAME,DOMAIN_ACCOUNT DOMINOCOUNT from hr_emp where 1=1";
                sql += " and (emp_no like '" + myParam + "%' or DOMAIN_ACCOUNT like '" + myParam + "%' or name like '" + myParam + "%')";


                ds = con.GetDateOracle(sql, connStrOracle);

            }
            context.Response.Write(ToJson(ds));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region  DataSet转换为Json
        /// <summary>   
        /// DataSet转换为Json  
        /// </summary>   
        /// <param name="dataSet">DataSet对象</param>  
        /// <returns>Json字符串</returns>   
        public static string ToJson(DataSet dataSet)
        {
            string jsonString = "{";
            foreach (DataTable table in dataSet.Tables)
            {
                jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
            }
            jsonString = jsonString.TrimEnd(',');
            return jsonString + "}";
        }
        #endregion

        #region Datatable转换为Json
        /// <summary>    
        /// Datatable转换为Json    
        /// </summary>   
        /// <param name="table">Datatable对象</param>    
        /// <returns>Json字符串</returns>    
        public static string ToJson(DataTable dt)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append("\"" + strKey + "\":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }
        /// <summary>   
        /// DataTable转换为Json    
        /// </summary>   
        public static string ToJson(DataTable dt, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName))
                jsonName = dt.TableName;
            Json.Append("{\"" + jsonName + "\":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Type type = dt.Rows[i][j].GetType();
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

        #endregion

        /// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        /// <param name="str"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static string StringFormat(string str, Type type)
        {
            if (type == typeof(string))
            {
                str = String2Json(str);
                str = "\"" + str + "\"";
            }
            else if (type == typeof(DateTime))
            {
                str = "\"" + str + "\"";
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = "\"" + str + "\"";
            }
            return str;
        }

        #region 私有方法
        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>json字符串</returns>
        private static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }
        #endregion
    }
}



 


 
  评论这张
 
阅读(606)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017