AJAX 无刷新3级联动下拉框

1.html代码
<HTML>
    <HEAD>
        <title>Ajax实现无刷新三联动下拉框</title>
        <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
        <meta content="C#" name="CODE_LANGUAGE">
        <meta content="JavaScript" name="vs_defaultClientScript">
        <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
        <SCRIPT language="javascript">            
            //城市------------------------------
            function cityResult() 
            { 
                var city=document.getElementById("DropDownList1");
                AjaxMethod.GetCityList(city.value,get_city_Result_CallBack);
            }
            
            function get_city_Result_CallBack(response)
            {
                if (response.value != null)
                {                    
                    //debugger;
                    document.all("DropDownList2").length=0;                
                var ds = response.value;
                    if(ds != null && typeof(ds) == "object" && ds.Tables != null)
                    {                    
                        for(var i=0; i<ds.Tables[0].Rows.length; i++)
                    {
                        var name=ds.Tables[0].Rows[i].city;
                      var id=ds.Tables[0].Rows[i].cityID;
                      document.all("DropDownList2").options.add(new Option(name,id));
                    }
                    }
                }                
                return
            }
            //市区----------------------------------------
            function areaResult() 
            { 
                var area=document.getElementById("DropDownList2");
                AjaxMethod.GetAreaList(area.value,get_area_Result_CallBack);
            }
            function get_area_Result_CallBack(response)
            {
                if (response.value != null)
                {                    
                    document.all("DropDownList3").length=0;                
                var ds = response.value;
                    if(ds != null && typeof(ds) == "object" && ds.Tables != null)
                    {                    
                        for(var i=0; i<ds.Tables[0].Rows.length; i++)
                    {
                      var name=ds.Tables[0].Rows[i].area;
                      var id=ds.Tables[0].Rows[i].areaID;
                      document.all("DropDownList3").options.add(new Option(name,id));
                    }                
                    }
                }
                return
            }
            function getData()
            {
                var province=document.getElementById("DropDownList1");
                var pindex = province.selectedIndex;
                var pValue = province.options[pindex].value;
                var pText  = province.options[pindex].text;
                
                var city=document.getElementById("DropDownList2"); var cindex = city.selectedIndex;
                var cValue = city.options[cindex].value;
                var cText  = city.options[cindex].text;
                
                var area=document.getElementById("DropDownList3");
                var aindex = area.selectedIndex;
                var aValue = area.options[aindex].value;
                var aText  = area.options[aindex].text;
                
                var txt=document.getElementById("TextBox1");                                

                document.getElementById("<%=TextBox1.ClientID%>").innerText="省:"+pValue+"|"+pText+"市:"+cValue+"|"+cText+"区:"+aValue+"|"+aText;
            }
        </SCRIPT>
    </HEAD>
    <body ms_positioning="GridLayout">
        <form id="Form1" method="post" runat="server">
            <TABLE id="Table1" style="Z-INDEX: 101; LEFT: 96px; POSITION: absolute; TOP: 32px" cellSpacing="1"
                cellPadding="1" width="300" border="1" bgColor="#ccff66">
                <TR>
                    <TD>省市</TD>
                    <TD><asp:dropdownlist id="DropDownList1" runat="server"></asp:dropdownlist></TD>
                </TR>
                <TR>
                    <TD>城市</TD>
                    <TD><asp:dropdownlist id="DropDownList2" runat="server"></asp:dropdownlist></TD>
                </TR>
                <TR>
                    <TD>市区</TD>
                    <TD><asp:dropdownlist id="DropDownList3" runat="server"></asp:dropdownlist></TD>
                </TR>
            </TABLE>
            <asp:TextBox id="TextBox1" style="Z-INDEX: 102; LEFT: 416px; POSITION: absolute; TOP: 48px" runat="server"
                Width="424px"></asp:TextBox><INPUT style="Z-INDEX: 103; LEFT: 456px; WIDTH: 56px; POSITION: absolute; TOP: 96px; HEIGHT: 24px"
                type="button" value="test" οnclick="getData();">
        </form>
    </body>
</HTML>

 

 

2.cs代码
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace AjaxTest
{
    /** <summary>
    /// Summary description for WebForm1.
    /// </summary>
    public class WebForm1 : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.DropDownList DropDownList1;
        protected System.Web.UI.WebControls.DropDownList DropDownList2;
        protected System.Web.UI.WebControls.TextBox TextBox1;
        protected System.Web.UI.WebControls.DropDownList DropDownList3;
    
        private void Page_Load(object sender, System.EventArgs e)
        {    
            Ajax.Utility.RegisterTypeForAjax(typeof(AjaxMethod));
            if(!Page.IsPostBack)
            {
                this.DropDownList1.DataSource=AjaxMethod.GetProvinceList();
                this.DropDownList1.DataTextField="province";
                this.DropDownList1.DataValueField="provinceID";
                this.DropDownList1.DataBind(); 
                this.DropDownList1.Attributes.Add("onclick","cityResult();");
                this.DropDownList2.Attributes.Add("onclick","areaResult();");
            }
        }

        Web Form Designer generated code#region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
        
        /** <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {    
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion        
    }
}

 

 

3.AjaxMethod
using System;
using System.Data;
using System.Data.SqlClient;
namespace AjaxTest
{
    /** <summary>
    /// Summary description for AjaxMethod.
    /// </summary>
    public class AjaxMethod
    {
        GetProvinceList#region GetProvinceList
        public static DataSet GetProvinceList()
        {
            string sql="select * from province";
            return GetDataSet(sql);
        }
        #endregion

        GetCityList#region GetCityList
        [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
        public  DataSet GetCityList(int provinceid)
        {
            string sql="select * from city where father="+provinceid;
            return GetDataSet(sql);            
        }
        #endregion

        GetAreaList#region GetAreaList
        [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
        public  DataSet GetAreaList(int cityid)
        {
            string sql="select * from area where father="+cityid;
            return GetDataSet(sql);            
        }
        #endregion
    
        GetDataSet#region GetDataSet
        public static DataSet GetDataSet(string sql)
        {
            string ConnectionString=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
            SqlDataAdapter    sda =new SqlDataAdapter(sql,ConnectionString);
            DataSet ds=new DataSet();
            sda.Fill(ds);
            return ds;
        }
        #endregion
    }
}
4.web.config
<httpHandlers>
            <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
    </httpHandlers>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 下拉框三级是一种常见的前端交互方式,可以通过AJAX实现。具体实现步骤如下: 1. HTML布局:使用select标签实现三个下拉框 ```html <select id="province"> <option value="">请选择省份</option> </select> <select id="city"> <option value="">请选择城市</option> </select> <select id="district"> <option value="">请选择区县</option> </select> ``` 2. JavaScript代码:使用jQuery库实现AJAX请求和DOM操作 ```javascript $(function(){ // 获取省份列表 $.ajax({ url: 'province.php', type: 'get', dataType: 'json', success: function(data){ // 遍历省份列表,添加到下拉框中 $.each(data, function(index, item){ $('#province').append('<option value="' + item.id + '">' + item.name + '</option>'); }); } }); // 省份下拉框改变事件 $('#province').change(function(){ var provinceId = $(this).val(); if(provinceId){ // 获取城市列表 $.ajax({ url: 'city.php', type: 'get', data: {provinceId: provinceId}, dataType: 'json', success: function(data){ // 清空城市和区县下拉框 $('#city').empty().append('<option value="">请选择城市</option>'); $('#district').empty().append('<option value="">请选择区县</option>'); // 遍历城市列表,添加到下拉框中 $.each(data, function(index, item){ $('#city').append('<option value="' + item.id + '">' + item.name + '</option>'); }); } }); }else{ // 清空城市和区县下拉框 $('#city').empty().append('<option value="">请选择城市</option>'); $('#district').empty().append('<option value="">请选择区县</option>'); } }); // 城市下拉框改变事件 $('#city').change(function(){ var cityId = $(this).val(); if(cityId){ // 获取区县列表 $.ajax({ url: 'district.php', type: 'get', data: {cityId: cityId}, dataType: 'json', success: function(data){ // 清空区县下拉框 $('#district').empty().append('<option value="">请选择区县</option>'); // 遍历区县列表,添加到下拉框中 $.each(data, function(index, item){ $('#district').append('<option value="' + item.id + '">' + item.name + '</option>'); }); } }); }else{ // 清空区县下拉框 $('#district').empty().append('<option value="">请选择区县</option>'); } }); }); ``` 3. 服务器端代码:根据省份和城市的ID获取对应的城市和区县列表,返回JSON格式数据 省份列表查询代码(省份表结构:id、name): ```php <?php // 连接数据库 $conn = mysqli_connect('localhost', 'root', '123456', 'test'); mysqli_set_charset($conn, 'utf8'); // 查询省份列表 $sql = 'select id, name from province'; $result = mysqli_query($conn, $sql); $data = array(); while($row = mysqli_fetch_assoc($result)){ $data[] = $row; } // 返回JSON格式数据 header('Content-Type: application/json; charset=utf-8'); echo json_encode($data); mysqli_close($conn); ?> ``` 城市列表查询代码(城市表结构:id、name、province_id): ```php <?php // 连接数据库 $conn = mysqli_connect('localhost', 'root', '123456', 'test'); mysqli_set_charset($conn, 'utf8'); // 获取省份ID $provinceId = $_GET['provinceId']; // 查询城市列表 $sql = 'select id, name from city where province_id = ' . $provinceId; $result = mysqli_query($conn, $sql); $data = array(); while($row = mysqli_fetch_assoc($result)){ $data[] = $row; } // 返回JSON格式数据 header('Content-Type: application/json; charset=utf-8'); echo json_encode($data); mysqli_close($conn); ?> ``` 区县列表查询代码(区县表结构:id、name、city_id): ```php <?php // 连接数据库 $conn = mysqli_connect('localhost', 'root', '123456', 'test'); mysqli_set_charset($conn, 'utf8'); // 获取城市ID $cityId = $_GET['cityId']; // 查询区县列表 $sql = 'select id, name from district where city_id = ' . $cityId; $result = mysqli_query($conn, $sql); $data = array(); while($row = mysqli_fetch_assoc($result)){ $data[] = $row; } // 返回JSON格式数据 header('Content-Type: application/json; charset=utf-8'); echo json_encode($data); mysqli_close($conn); ?> ``` 以上代码仅供参考,具体实现需要根据实际情况进行调整。 ### 回答2: Ajax实现下拉框三级的主要步骤如下: 1. 配置HTML页面:在HTML页面中创建三个下拉框的元素,并分别设置一个id,用于后续的JavaScript操作。 2. 编写JavaScript代码:使用JavaScript监听第一个下拉框的改变事件。当第一个下拉框选中的选项发生改变时,触发事件处理程序。 3. 使用Ajax发送异步请求:在事件处理程序中,使用Ajax发送异步请求到服务器,以获取与第一个下拉框选中选项相关联的第二个下拉框选项。 4. 服务器端处理请求:服务器端根据第一个下拉框选中的选项,查询数据库或者调用API,获取与之相关联的第二个下拉框选项,并将数据以JSON格式返回给前端。 5. 更新第二个下拉框选项:前端接收到服务器返回的数据后,使用JavaScript态添加或替换第二个下拉框的选项。 6. 同样地,在第二个下拉框的改变事件中,触发事件处理程序,并通过Ajax发送异步请求获取与第二个下拉框选中选项相关联的第三个下拉框选项。 7. 更新第三个下拉框选项:前端接收到服务器返回的数据后,使用JavaScript态添加或替换第三个下拉框的选项。 通过以上步骤,就可以实现下拉框三级效果。需要注意的是,要正确处理在选择某个下拉框选项时,下级下拉框的选项需要相应改变。另外,在发送Ajax请求时需要考虑兼容性和请求的性能,可以使用jQuery等库来简化代码,并提高发送请求的效率。 ### 回答3: Ajax实现下拉框三级的原理是通过前端页面的JavaScript代码和后端服务器之间的异步请求来实现数据的态加载和更新。 首先,我们需要创建三个下拉框元素,分别用于显示一级、二级和三级的选项。通过监听一级下拉框的变化事件,我们可以在JavaScript代码中获取到用户选择的一级选项的值。 接下来,我们需要使用Ajax技术向后端服务器发送异步请求,获取对应一级选项的二级选项数据。通过Ajax发送GET或POST请求,并将一级选项的值作为参数传递给后端服务器,服务器根据参数的值查询数据库或其他数据源,返回对应的二级选项数据。 当从服务器端获取到二级选项数据后,我们可以使用JavaScript态地更新二级下拉框的选项。此时,我们同样需要监听二级下拉框的变化事件,以获取用户选择的二级选项的值。 然后,我们再次使用Ajax技术向后端服务器发送异步请求,获取对应二级选项的三级选项数据。服务器根据二级选项的值查询数据库或其他数据源,返回对应的三级选项数据。 当从服务器端获取到三级选项数据后,我们可以使用JavaScript态地更新三级下拉框的选项。 通过以上操作,我们就可以实现下拉框三级效果。用户选择一级选项后,二级选项会根据一级选项的值进行态更新;用户选择二级选项后,三级选项会根据二级选项的值进行态更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值