1. 程式人生 > >AJAX——動態新增控制元件(複選框)

AJAX——動態新增控制元件(複選框)

需求:使用者根據自己的需求,配置下拉框中的欄位。

解決思路:使用者配置下拉框中的欄位(例如:高階查詢,基礎資訊),動態新增複選框控制元件。使用者再對複選框進行勾選,最終結果是,基礎資訊中的,高階查詢下拉框中為使用者勾選的欄位。

前臺程式碼:

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="location">
        當前位置:設定->:下拉框欄位
    </div>
    <table style="width: 100%;" cellpadding="6" cellspacing="1" class="border">
        <tr>
            <td align="center" class="auto-style1">
                <asp:DropDownList ID="ddlFieldType" runat="server" Style="margin-left: 40px" Height="20px" Width="140px">
                </asp:DropDownList>
                <asp:DropDownList ID="ddlMenuIndex" runat="server" Style="margin-left: 60px" Height="20px" Width="140px" OnChange="javascript:SetData()">
                </asp:DropDownList>
            </td>
            <td></td>
        </tr>
    </table>
    <br />
    <br />

    <div id="divCheckBox">
    </div>


</asp:Content>


後臺程式碼:

 //例項化系統設定外觀
        Facade.SystemSetFacade systemSetFacade = new Facade.SystemSetFacade();
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)               //判斷頁面是否第一次載入
            {
                //動態為下拉框新增欄位
                SqlDataReader sdr = systemSetFacade.getMenu();
                ddlMenuIndex.DataSource = sdr;
                ddlMenuIndex.DataTextField = "menuChinesename";
                ddlMenuIndex.DataValueField = "menuEnglishname";
                ddlMenuIndex.DataBind();
                this.ddlMenuIndex.Items.Insert(0, "--請選擇--");

                ListItem ListItem1 = new ListItem("高階查詢", "advancedQuery");
                ListItem ListItem2 = new ListItem("批量修改", "largeModify");
                this.ddlFieldType.Items.Add(ListItem1);
                this.ddlFieldType.Items.Add(ListItem2);
                this.ddlFieldType.Items.Insert(0, "--請選擇--");

                //AjaxPro.Utility.RegisterTypeForAjax(typeof(FieldSet));
            }
        }

實現介面:

                                             

使用者配置好上圖中的下拉框,頁面動態建立多個。

動態新增控制元件的JS程式碼:

 </style>
    <script type="text/javascript"  charset="gbk" >

        //動態新增複選框
        function SetData() {
            
            var strMenuIndexID = document.getElementById("ctl00_ContentPlaceHolder1_ddlMenuIndex");     
            var strFieldTypeID = document.getElementById("ctl00_ContentPlaceHolder1_ddlFieldType");
            //使用者選擇的選單項:基礎資訊等
            var strMenuIndexValue = strMenuIndexID.options[strMenuIndexID.selectedIndex].value;
            //使用者選擇下拉框類別:高階查詢、批量修改
            var strFieldTypeValue = strFieldTypeID.options[strFieldTypeID.selectedIndex].value;
            //處理編號:多個ajax請求,為每一個進行編號
            var dealID = "001";
            //判斷選擇選單項的下拉框是否為空
            if ("" == strMenuIndexValue) {
                alert("請選擇選單!");
            //判斷選擇下拉框類別的下拉框是否為空
            } else if ("" == strFieldTypeValue) {
                alert("請選擇下拉框類別!");
            } else {

                //後臺查詢資料庫,取得為新增複選框需要的資料
                $.ajax({
                    //get方式傳送請求
                    type: "get",
                    //將要訪問FieldSet.ashx一般處理程式
                    //傳遞的引數有:處理編號,選擇的選單項,時間(為了避免獲得快取)
                    url: "FieldSet.ashx?dealID=" + dealID + "&strMenuIndexValue=" + strMenuIndexValue + "&t=" + new Date().getTime(),
                    //將伺服器返回的結果,以strJson接收
                    success: function (strJson) {
                        var obj = eval(strJson);
                        //開始建立複選框
                        addCheckBox(obj);
                    },

                    error: function (XmlHttpRequest, textStatus, errorThrown) {
                        alert(XmlHttpRequest.responseText);
                    }
                });
            }
        }

        //新增複選框的方法
        function addCheckBox(obj) {
            var i;
            //var inHTML;

            //獲得前臺的div
            var insertDiv = document.getElementById("divCheckBox");
            //定義向前臺插入的內容為空
            insertDiv.innerHTML = "";
            var chkinfo;
            var chkDIV;
            //var txtinfo;
            //解析從伺服器獲得的資料,迴圈新增複選框
            for (i = 0; i < obj.length; i++) {
                //為每一個複選框建立一個DIV
                chkDIV = document.createElement("div");
                //每一個複選框用input建立,型別為checkBox
                chkinfo = document.createElement("input");
                chkinfo.name = "checkboxid";
                chkinfo.id = obj[i].chinesename;
                chkinfo.type = "checkbox";
                chkinfo.onclick = test;
                //將每一個chinesename為複選框賦值
                chkinfo.value = obj[i].chinesename;
               //將複選框新增到Div中
                chkDIV.appendChild(chkinfo);
                //為Div設定樣式
                chkDIV.style.height = "50px";
                chkDIV.style.width = "150px";
                chkDIV.style.float = "left";
                chkDIV.align = "left";
                chkDIV.appendChild(document.createTextNode(obj[i].chinesename));
                //將建立的div新增到前臺預留的DIV下
                insertDiv.appendChild(chkDIV);        
            }

            var strMenuIndexID = document.getElementById("ctl00_ContentPlaceHolder1_ddlMenuIndex");
            var strFieldTypeID = document.getElementById("ctl00_ContentPlaceHolder1_ddlFieldType");
            var strMenuIndexValue = strMenuIndexID.options[strMenuIndexID.selectedIndex].value;
            var strFieldTypeValue = strFieldTypeID.options[strFieldTypeID.selectedIndex].value;
            //處理編號
            var dealID = "002";
            //後臺查詢資料庫,獲取配置下拉框中目前存在的欄位
            $.ajax({
                type: "get",
                url: "fieldSet.ashx?dealID=" + dealID + "&strMenuIndexValue=" + strMenuIndexValue + "&strFieldTypeValue=" + strFieldTypeValue+ "&t=" + new Date().getTime(),
                success: function (strJsonSelected) {
                    if (strJsonSelected != "") {
                        var obj = eval(strJsonSelected);
                        selectedFields = new Array(obj.length)
                        for (i = 0; i < obj.length; i++) {
                            //將下拉框中目前存在的欄位進行勾選
                            (document.getElementById(obj[i].fieldName)).checked = true;
                        }
                    }
                }
            })
        }

        //動態向下拉框中配置欄位
        var test = function updateField() {
            //動態向下拉框新增
            if (this.checked == true) {
                //(this.value+"true");
                var selectedFeild = this.value;
                var strMenuIndexID = document.getElementById("ctl00_ContentPlaceHolder1_ddlMenuIndex");
                var strFieldTypeID = document.getElementById("ctl00_ContentPlaceHolder1_ddlFieldType");
                var strMenuIndexValue = strMenuIndexID.options[strMenuIndexID.selectedIndex].value;
                var strFieldTypeValue = strFieldTypeID.options[strFieldTypeID.selectedIndex].value;
                //定義控制元件勾選狀態變數
                var fieldSelectedState = "true";
                //處理編號
                var dealID = "003";
               //後臺將使用者勾選的欄位,新增到資料庫
                $.ajax({
                    type: "get",
                    url: "fieldSet.ashx?dealID=" + dealID + "&strMenuIndexValue=" + strMenuIndexValue + "&strFieldTypeValue=" + strFieldTypeValue + "&selectedFeild=" + escape(selectedFeild) + "&fieldSelectedState=" + fieldSelectedState + "&t=" + new Date().getTime(),
                    success: function (isInsert) {                     
                        if (isInsert == 'True') {
                            alert("下拉框成功新增此欄位!");
                        }
                    }
                })
            }
            else {
                //alert(this.value + "false");
                var selectedFeild = this.value;
                var strMenuIndexID = document.getElementById("ctl00_ContentPlaceHolder1_ddlMenuIndex");
                var strFieldTypeID = document.getElementById("ctl00_ContentPlaceHolder1_ddlFieldType");
                var strMenuIndexValue = strMenuIndexID.options[strMenuIndexID.selectedIndex].value;
                var strFieldTypeValue = strFieldTypeID.options[strFieldTypeID.selectedIndex].value;

                var fieldState = "false";
                var dealID = "003";
                //使用者取消勾,後臺將刪除此欄位
                $.ajax({
                    type: "get",
                    url: "fieldSet.ashx?dealID=" + dealID + "&strMenuIndexValue=" + strMenuIndexValue + "&strFieldTypeValue=" + strFieldTypeValue + "&selectedFeild=" + escape(selectedFeild) + "&fieldSelectedState=" + fieldSelectedState + "&t=" + new Date().getTime(),
                    success: function (isDelete) {
                        if (isDelete == 'True') {
                            alert("下拉框成功刪除此欄位!");
                        }
                    }
                })
            }
        }
    </script>


後臺一般處理程式程式碼:

public class FieldSet1 : IHttpHandler
    {

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

            //例項化系統設定外觀
            Facade.SystemSetFacade systemSetFacade = new Facade.SystemSetFacade();
            var dealID = context.Request.QueryString["dealID"];

            //後臺讀取資料庫,為動態新增複選框提供資料
            if (dealID == "001")
            {

                string strMenuIndexValue = context.Request.QueryString["strMenuIndexValue"];
                DataTable dtFields = new DataTable();
                //查詢下拉框課配置的欄位
                dtFields = systemSetFacade.itemQuery(strMenuIndexValue);

                string strJson = DataTableToJson("FieldsJson", dtFields);
                context.Response.Write(strJson);
                context.Response.End();

            }
             //後臺查詢資料庫,返回下拉框中已存在的欄位
            else if (dealID == "002")
            {
                string strMenuIndexValue = context.Request.QueryString["strMenuIndexValue"];
                string strFieldTypeValue = context.Request.QueryString["strFieldTypeValue"];
                int dtCount;
                DataTable dtSelectedFields = new DataTable();
                dtSelectedFields = systemSetFacade.itemSelectedQuery(strMenuIndexValue, strFieldTypeValue);
                dtCount = dtSelectedFields.Rows.Count;
                if (dtCount > 0)
                {
                    string strJsonSelected = DataTableToJson("FieldsJson", dtSelectedFields);
                    context.Response.Write(strJsonSelected);
                    context.Response.End();
                }
                else
                {
                    string strJsonSelected = "";
                    context.Response.Write(strJsonSelected);
                }
            }
                //隨著使用者勾選、取消勾選,動態將資料新增到資料庫中
            else if (dealID == "003")
            {
                string selectedFeild = context.Request.QueryString["selectedFeild"];
                string strMenuIndexValue = context.Request.QueryString["strMenuIndexValue"];
                string strFieldTypeValue = context.Request.QueryString["strFieldTypeValue"];
                string fieldSelectedState = context.Request.QueryString["fieldSelectedState"];
                //使用者勾選複選框,將勾選欄位新增到資料庫中
                if (fieldSelectedState == "true")
                {
                    Boolean isInsert;
                    isInsert = systemSetFacade.insertField(strMenuIndexValue, strFieldTypeValue, selectedFeild);
                    context.Response.Write(isInsert);
                }
                //使用者取消勾選,將取消勾選的欄位從資料庫中刪除
                else
                {
                    Boolean isDelete;
                    isDelete = systemSetFacade.deleteField(strMenuIndexValue, strFieldTypeValue, selectedFeild);
                    context.Response.Write(isDelete);
                }

            }

        }

        //將從資料庫中讀取的表,轉成Json
        public string DataTableToJson(string jsonName, DataTable dt)
        {

            StringBuilder Json = new StringBuilder();
            Json.Append("[");
            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++)
                    {
                        Json.Append(dt.Columns[j].ColumnName.ToString() + ":\"" + dt.Rows[i][j].ToString() + "\"");
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]");
            return Json.ToString();
        }


效果圖:

 

                                         

基礎資訊——高階查詢的下拉框:

    
                     

至此,這動態配置下拉框欄位暫且完成了。主要用Ajax來實現頁面部分更新。通過這些,比較深刻的認識了Ajax。