ajax+js省市联动

来源:互联网 发布:开淘宝网店在哪进货 编辑:程序博客网 时间:2024/04/30 15:59
********************js********************
<script type="text/javascript">
  var xmlHttp;
    function createHttp()
    {
        if(window.ActiveXObject)
        {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else
        { 
            xmlHttp = new XMLHttpRequest();
        }
    }
    function getCities()
    {
        var url = "${base}/cms/action/agencyRegister!showCity.action?id="+document.getElementById("province").value;
        createHttp();
        xmlHttp.onreadystatechange=showRes;
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    }
    function showRes()
    {
        if(xmlHttp.readyState==4)
        {
           if(xmlHttp.status==200)
           {
           addCity();
           }
        }
    }
    function addCity(){
         var citys = document.getElementById("city");
         clearOptions(citys);
         var txt = xmlHttp.responseText;
         var res;
         eval('res=' + txt);
$.each(res, function(i) {
var opt = document.createElement("option");
opt.text=res[i].NAME;
opt.value=res[i].CODE;
citys.options.add(opt);
});


     }
     function clearOptions(citys)
     {
           for( var i=citys.options.length;i>-1;i--)
            {
               citys.options.remove(i);
            }
     }

</script>



********************html*******************
<select  class="inpu1 w150" id="province"  name="provinceCode.code" onchange="getCities()"><#--省市这里涉及到直辖市的问题得改一改-->
     <option value="">--省--</option>
     <#list provinceList as province>
        <option value="${province.CODE}">${province.NAME}</option>
     </#list>
</select>
     <span class="lianjiexian">-</span>
     <select class="inpu1 w150" id="city" name="cityCode.code">
     <option value="">--市--</option>
</select>


********************后台***********************
/**
* 获取城市
* @return
*/
public String showCity(){
ActionContext ctx = ActionContext.getContext();
HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
String provinceId = request.getParameter("id");
List<CityEntity> cityList = agencyRegisterService.getCity(provinceId);
JsonConfig jsonConfig = new JsonConfig();
JSONArray jsonArray = JSONArray.fromObject(cityList, jsonConfig);
return ajaxJson(jsonArray.toString());
}
0 0
原创粉丝点击