jQuery实现三级联动

本文介绍使用jQuery的AJAX功能和asp.net来实现省市区的三级联动效果,其他二级、三级或多级联动也可以按照此方法完成。

本文介绍使用jQuery的AJAX功能和asp.net来实现省市区的三级联动效果,其他二级、三级或多级联动也可以按照此方法完成。

文章中涉及到的数据表为City,为方便管理。

设计此表如下

ID:自增长字段

City_Name:城市名称

City_Code:城市代码

我们根据城市代码来查询省、市、区。城市代码结构大致如下:

内蒙古:150000,呼和浩特:150100,新城区:150101。

其他地区代码与此一样,省级为省级编号+0000,市级为省级编号+市级编号+00,地区为省级编号+市级编号+地区编号。

City.ASPX代码为:

 
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head runat="server">
  4.     <title>jQuery + ASP.NET实现三级联动</title>
  5.     <script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
  6.     <style type="text/css">
  7.         #dpCity{ display:none; position:relative;}
  8.         #dpArea{ display:none;position:relative;}
  9.     </style>
  10. </head>
  11. <body>
  12.     <div>
  13.         省:<asp:DropDownList ID="dpProvince" runat="server"></asp:DropDownList>&nbsp;&nbsp;
  14.         市:<asp:DropDownList ID="dpCity" runat="server"></asp:DropDownList>&nbsp;&nbsp;
  15.         区:<asp:DropDownList ID="dpArea" runat="server"></asp:DropDownList>
  16.     </div>
  17. </body>
  18. </html>

JS代码:

 
  1. jQuery(document).ready(function () {
  2.             var dp1 = jQuery("#dpProvince");
  3.             var dp2 = jQuery("#dpCity");
  4.             var dp3 = jQuery("#dpArea");
  5.             //填充省的数据
  6.             loadAreas("""dpProvince");
  7.             //给省绑定事件,触发事件后填充市的数据
  8.             jQuery(dp1).bind("change keyup"function () {
  9.                 var provinceID = dp1.attr("value");
  10.                 loadAreas(provinceID, "dpCity");
  11.                 dp2.fadeIn("slow");
  12.             });
  13.             //给市绑定事件,触发事件后填充区的数据
  14.             jQuery(dp2).bind("change keyup"function () {
  15.                 var cityID = dp2.attr("value");
  16.                 loadAreas(cityID, "dpArea");
  17.                 dp3.fadeIn("slow");
  18.             });
  19.         });
  20.         function loadAreas(val, item) {
  21.             jQuery.ajax({
  22.                 type: "post",
  23.                 url: "CityLoader.asmx/GetCityList",
  24.                 data: {
  25.                     code: val,
  26.                     a: Math.random()
  27.                 },
  28.                 error: function () {
  29.                     return false;
  30.                 },
  31.                 success: function (data) {
  32.                     var i;
  33.                     var json = eval(data);
  34.                     jQuery("#" + item).append("<option value='' selected='selected'>请选择</option>");
  35.                     for (i = 0; i < json.length; i++) {
  36.                         jQuery("#" + item).append(jQuery("<option></option>").val(json[i].c_code).html(json[i].c_name));
  37.                     };
  38.                 }
  39.             });
  40.         }

后台代码:

 
  1. //实例类
  2. public class CityModel
  3.     {
  4.         int _id;
  5.         string _cityname;
  6.         string _citycode;
  7.         public int ID
  8.         {
  9.             set { _id = value; }
  10.             get { return _id; }
  11.         }
  12.         public string CityName
  13.         {
  14.             set { _cityname = value; }
  15.             get { return _cityname; }
  16.         }
  17.         public string CityCode
  18.         {
  19.             set { _citycode = value; }
  20.             get { return _citycode; }
  21.         }
  22.     }
  23. //DAL层,返回DataTable,使用通用SqlHelper
  24. public DataTable CityList(string pcode)
  25.         {
  26.             string SQL = "SELECT * FROM city WHERE 1=1";
  27.             if (!string.IsNullOrEmpty(pcode))
  28.             {
  29.                  if (pcode.Substring(2, 2) != "00")
  30.                 {
  31.                     SQL = SQL + " AND RIGHT(citycode,2)<>'00' AND LEFT(citycode,4)=LEFT(@pcode,4)";
  32.                 }
  33.                 else
  34.                 {
  35.                     SQL = SQL + " AND RIGHT(citycode,2)='00' AND LEFT(RIGHT(citycode,4),2)<>'00' AND LEFT(citycode,2)=LEFT(@pcode,2)";
  36.                 }
  37.             }
  38.             else
  39.             {
  40.                 SQL = SQL + " AND LEFT(citycode,2)<>'00' AND RIGHT(citycode,4)='0000'";
  41.             }
  42.             SQL = SQL + " ORDER BY sorts ASC";
  43.             SqlParameter[] Param ={
  44.                 new SqlParameter("@pcode",pcode)
  45.             };
  46.             using (SqlConnection conn = new SqlConnection(DBUtility.SqlHelper.ConnectionStringLocalTransaction))
  47.             {
  48.                 DataSet ds = DBUtility.SqlHelper.ExecuteDataSet(conn, CommandType.Text, SQL, Param);
  49.                 return ds.Tables[0];
  50.             }
  51.         }
  52. //BLL层,返回City的泛型列表
  53.  public List<CityModel> CityList(string code)
  54.         {
  55.             List<CityModel> list = new List<CityModel>();
  56.            DAL. CityDAL cd = new DAL.CityDAL();
  57.             DataTable dt = cd.CityList(code);
  58.             if (dt.Rows.Count > 0)
  59.             {
  60.                 for (int i = 0; i < dt.Rows.Count; i++)
  61.                 {
  62.                     CityModel cm = new CityModel();
  63.                     cm.ID = int.Parse(dt.Rows[i]["id"].ToString());
  64.                     cm.CityName = dt.Rows[i]["cityname"].ToString();
  65.                     cm.CityCode = dt.Rows[i]["citycode"].ToString();
  66.                     list.Add(cm);
  67.                 }
  68.             }
  69.             return list;
  70.         }

CityLoader.asmx:

 
  1. /// <summary>
  2.     /// CityLoader 的摘要说明
  3.     /// </summary>
  4.     [WebService(Namespace = "http://tempuri.org/")]
  5.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  6.     [System.ComponentModel.ToolboxItem(false)]
  7.     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
  8.     // [System.Web.Script.Services.ScriptService]
  9.     public class CityLoader : System.Web.Services.WebService
  10.     {
  11.         [WebMethod]
  12.         public void GetCityList(string code)
  13.         {
  14.             CityBLL cb = new CityBLL();
  15.             StringBuilder sb = new StringBuilder();
  16.             List<CityModel> cm = cb.CityList(code);
  17.             sb.Append("[");
  18.             if (cm.Count > 0)
  19.             {
  20.                 for (int i = 0; i < cm.Count; i++)
  21.                 {
  22.                     CityModel model = cm[i];
  23.                     sb.Append("{");
  24.                     sb.AppendFormat(@"""c_name"":""{0}"",", model.CityName);
  25.                     sb.AppendFormat(@"""c_code"":""{0}""", model.CityCode);
  26.                     sb.Append("}");
  27.                     if (i < cm.Count - 1)
  28.                     {
  29.                         sb.Append(",");
  30.                     }
  31.                 }
  32.             }
  33.             sb.Append("]");
  34.             System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
  35.             System.Web.HttpContext.Current.Response.Write(sb.ToString());
  36.         }
  37.     }
posted @ 2012-05-29 14:58  PointNet  阅读(11067)  评论(0编辑  收藏  举报