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",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,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。

原文链接:https://www.f2er.com/ajax/164864.html

猜你在找的Ajax相关文章