JQuery+WebService实现DropDownlist无刷新三级联动

本文的一些内容是参考互联网上的,所以有部分是相似的,请原作者谅解(时间久远,找不到出处了).

 

一,数据源为SQL Server

采用的是国内的省市县三级的数据库.具体的数据库请看脚本.
https://files.cnblogs.com/conan304/CitySQL.zip

 

二,前台代码端

    地址:&nbsp; &nbsp;<asp:DropDownList ID="ddlProvince" runat="server"></asp:DropDownList>
   
&nbsp; &nbsp; <asp:DropDownList ID="ddlCity" runat="server"></asp:DropDownList> 

   &nbsp;&nbsp;<asp:DropDownList ID="ddlArea" runat="server"></asp:DropDownList>

   

三,Jquery代码

<script type="text/javascript" language="javascript" src="Script/jquery-1.4.1.min.js"></script>
<script type="text/javascript" language="javascript">
    $(
function() {         

        
var $dp1 = $("#ddlProvince");
        
var $dp2 = $("#ddlCity");
        
var $dp3 = $("#ddlArea");
        $dp1.focus();

        loadAreas(
"0""0");

        $dp2[
0].disabled = true;
        $dp3[
0].disabled = true;

        $dp1.bind(
"change keyup"function() {
            
if ($(this).val() != "") {
                
var strPid = $dp1.attr("value"); //获取城市
                loadAreas(strPid, "1");
                $dp2[
0].disabled = false;
            } 
else {
                $dp2[
0].disabled = true;
                $(
"#ddlCity").html("");
                $(
"#ddlCity").append("<option value='' selected='selected'>请选择城市名称</option>");

                $(
"#ddlArea").html("");
                $(
"#ddlArea").append("<option value='' selected='selected'>请选择地区名称</option>");
            }
            $dp3[
0].disabled = true;
        });
        $dp2.bind(
"change keyup"function() {
            
var strCId = $dp2.attr("value"); //获取城市
            if ($(this).val() != "") {
                loadAreas(strCId, 
"2");
                $dp3[
0].disabled = false;
            } 
else {
                $dp3[
0].disabled = true;
                $(
"#ddlArea").html("");
                $(
"#ddlArea").append("<option value='' selected='selected'>请选择地区名称</option>");
            }
        });
    });

    
function loadAreas(selectedItem, level) {
        $.ajax({
            type: 
"GET",
            contentType: 
"application/json; charset=utf-8",
            url: 
"Ajax/CityGet.asmx/CityInfoGet",
            data: encodeURI(
"parentID='" + selectedItem + "'"),
            dataType: 
"json",
            success: 
function(result) {
                
switch (level) {
                    
case "0":
                        $(
"#ddlProvince").html("");
                        $(
"#ddlProvince").append("<option value='' selected='selected'>请选择省份</option>");

                        $(
"#ddlCity").html("");
                        $(
"#ddlCity").append("<option value='' selected='selected'>请选择城市名称</option>");

                        $(
"#ddlArea").html("");
                        $(
"#ddlArea").append("<option value='' selected='selected'>请选择地区名称</option>");

                        
for (var i = 0; i < result["d"].length; i++) {
                            $(
"#ddlProvince").append($("<option></option>").val(result["d"][i].CodeID).html(result["d"][i].CityName));
                        };
                        
break;
                    
case "1":
                        $(
"#ddlCity").html("");
                        $(
"#ddlCity").append("<option value='' selected='selected'>请选择城市名称</option>");

                        $(
"#ddlArea").html("");
                        $(
"#ddlArea").append("<option value='' selected='selected'>请选择地区名称</option>");

                        
for (var i = 0; i < result["d"].length; i++) {
                            $(
"#ddlCity").append($("<option></option>").val(result["d"][i].CodeID).html(result["d"][i].CityName));
                        };
                        
break;
                    
case "2":
                        $(
"#ddlArea").html("");
                        $(
"#ddlArea").append("<option value='' selected='selected'>请选择地区名称</option>");
                        
for (var i = 0; i < result["d"].length; i++) {
                            $(
"#ddlArea").append($("<option></option>").val(result["d"][i].CodeID).html(result["d"][i].CityName));
                        };
                        
break;

                    
default:
                        
break;
                }

            },
            error: 
function(x, e) {
                alert(x.responseText);
            }
        });
    }

</script> 


 

四,c#代码 

1,WebService,位于AJAX文件夹下:

using System.Collections.Generic;
using System.Web.Script.Services;
using System.Web.Services;

/// <summary>
///CityGet 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo 
= WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
 [System.Web.Script.Services.ScriptService]
public class CityGet : System.Web.Services.WebService
{

    
public CityGet()
    {

        
//如果使用设计的组件,请取消注释以下行 
        
//InitializeComponent(); 
    }


    
/// <summary>
    
/// 获取城市信息,用Json返回
    
/// </summary>
    
/// <param name="parentID"></param>
    
/// <returns></returns>
    [WebMethod]
    [ScriptMethod(ResponseFormat 
= ResponseFormat.Json, UseHttpGet = true)]
    
public IList<Model.CityInfo> CityInfoGet(string parentID)
    {
        IList
<Model.CityInfo> list = BLL.City.CityInfo.CityListFindByParentID(int.Parse(parentID));
        
return list;
    }


 

 多层架构调用,省略了中间的DALFactory,IDal等.这里仅仅写出访问数据库的代码:

using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace SQLServer.City
{
    
public class CityInfo : IDAL.City.ICityInfo
    {
        
/// <summary>
        
/// 根据父级ID获取城市信息
        
/// </summary>
        
/// <param name="CodeID"></param>
        
/// <returns></returns>
        public IList<Model.CityInfo> CityListFindByParentID(int CodeID)
        {
            IList
<Model.CityInfo> listCity = new List<Model.CityInfo>();

            StringBuilder sql 
= new StringBuilder();
            sql.Append(
"    SELECT [codeid],[parentid],[cityName]");
            sql.Append(
"    FROM [tbl_province]");
            sql.Append(
"    WHERE parentid=@parentid");            
            sql.Append(
"    ORDER BY codeid");

            SqlParameter param 
= new SqlParameter("@parentid", SqlDbType.Int);
            param.Value 
= CodeID;


            
using (SqlDataReader dr = SQLHelper.ExecuteReader(CommandType.Text, sql.ToString(), param))
            {
                
while (dr.Read())
                {
                    Model.CityInfo city 
= new Model.CityInfo
                    {
                        CodeID 
= dr.GetInt32(0),
                        ParentID 
= dr.GetInt32(1),
                        CityName 
= dr.GetString(2).Trim()
                    };
                    listCity.Add(city);
                }
            }

            
return listCity;
        }
    }

 

Model:

namespace Model
{
    
/// <summary>
    
/// 城市信息
    
/// </summary>
    public class CityInfo
    {
        
/// <summary>
        
/// 城市的ID
        
/// </summary>
        public int CodeID { getset; }

        
/// <summary>
        
/// 城市的父级ID
        
/// </summary>
        public int ParentID { getset; }

        
/// <summary>
        
/// 城市的名称
        
/// </summary>
        public string CityName { getset; }
    }

}  


 

posted @ 2011-07-31 10:25  Conan304  阅读(454)  评论(2编辑  收藏  举报