通过ajax 绑定 国家地区联动下拉列表

上章写到不用ajax进行关联,现记录下通过ajax绑定国家地区下拉列表

js:

View Code
//地区下拉
 function changeRegion(stateid, controlsid,showSelect) {

     if (stateid != "0") {

         $.ajax({
             type: "POST",
             url: "Ajax/Region.ashx?action=changeRegion&id=" + stateid,
             data: "yshop=yshop",
             async: false,
             dataType: "JSON",
             success: function (data, df) {
                 var json = eval('(' + data + ')');
                 changeResponse(json, stateid, controlsid, showSelect);
             }
         });
     }
 }
 function changeResponse(result, stateid, controlsid, showSelect) {
     var sel = document.getElementById(controlsid); 
     if (result.error == 0) { 
         sel.length = 0;
         var goods = result.content.goods;
         if (showSelect != "") {
             var opt = document.createElement("OPTION");
             opt.value = "0";
             opt.text = showSelect;
             sel.options.add(opt);
         }
         if (goods.length) {
             for (i = 0; i < goods.length; i++) {
                 var opt = document.createElement("OPTION");
                 opt.value = goods[i].goods_id;
                 opt.text = goods[i].goods_name;
                 if (stateid == goods[i].goods_id) {
                     opt.selected = true; //默认选择
                 }
                 sel.options.add(opt);
             }
         }
     }
     if (result.message.length > 0) {
         alert(result.message);
     }
 }

html:

<asp:DropDownList ID="ddlstate" runat="server"  onchange="changeRegion(this.value,'ddlcity','')">
             <asp:ListItem Value="0">请选择</asp:ListItem>
            </asp:DropDownList>    
            <asp:DropDownList ID="ddlcity" runat="server">
             <asp:ListItem Value="0">请选择</asp:ListItem>
            </asp:DropDownList>

<script type="text/javascript">

    $(function () {
        
      
        changeRegion("1", "ddlstate","");
       
    });
   
 </script>

c#:

 
//http://www.cnblogs.com/yfdong22
public static string GetRegionNameAndIDOption(string keywords, string strWhere) { Glant.BLL.BLLRegion bll = new Glant.BLL.BLLRegion(); List<Model.ModelRegion> list = bll.GetModelList("parent_id=" + keywords + " " + strWhere); System.Text.StringBuilder sbjson = new System.Text.StringBuilder(); if (list.Count > 0) { foreach (Model.ModelRegion model in list) { sbjson.Append("{\"goods_id\":\"" + model.region_id.ToString() + "\",\"goods_name\":\"" + model.region_name.ToString() + "\"},"); } } return "{\"content\":{\"goods\":[" + sbjson.ToString() + "]},\"message\":\"\",\"error\":\"0\"}"; }

myblog:http://www.cnblogs.com/yfdong22

地区数据mysql:下载页面:http://ishare.iask.sina.com.cn/f/4950333.html

posted @ 2012-08-18 10:52  mrcoolye  阅读(306)  评论(0编辑  收藏  举报