JS+AJAX realizes the linkage of province, city and district drop-down lists

JS+AJAX realizes the linkage of province, city and district drop-down lists

This article shares the specific code of JS+AJAX to realize the linkage of province, city and district drop-down lists for your reference. The specific content is as follows

The effect diagram is as follows, the data stored in the DB is extracted.

Implementation of front-end JSP page

<div class="info">
<div class="title">Company Address:</div>
<div class="value">
<fieldset disabled>
<select id="provinceSelect" class="form-control" data-val="${factoryCenterInfo.province}" onchange="provinceChange()">
<c:forEach items="${factoryPlace.provinceList}" var="province" varStatus="status">
<option value="${province.key}" <span style="color:#3333ff;"><c:if test="${factoryCenterInfo.province == province.key}">selected</c:if></span><span style="color:#3366ff;">></span>${province.value}</option>
</c:forEach>
</select>
</fieldset>
<fieldset disabled>
<select id="citySelect" class="form-control" data-val="${factoryCenterInfo.city}" onchange="cityChange()">
<c:forEach items="${factoryPlace.cityList}" var="city" varStatus="status">
<option value="${city.key}" <span style="color:#3333ff;"><c:if test="${factoryCenterInfo.city == city.key}">selected</c:if></span>>${city.value}</option>
</c:forEach>
</select>
</fieldset>
<fieldset disabled>
<select id="areaSelect" class="form-control" data-val="${factoryCenterInfo.area}">
<c:forEach items="${factoryPlace.areaList}" var="area" varStatus="status">
<option value="${area.key}" <span style="color:#3333ff;"><c:if test="${factoryCenterInfo.area == area.key}">selected</c:if></span>>${area.value}</option>
</c:forEach>
</select>
</fieldset>
</div>
</div>

JS implementation code

Effect: Implement multiple ajax requests and search data in a linked manner

function provinceChange(){
 
 var provinceId = $("#provinceSelect").val();
 $("#citySelect").empty();
 $("#areaSelect").empty();
 
 if(provinceId != null && provinceId != ""){
  
  $.ajax({
   type: "POST",
   url:"<span style="color:#3333ff;">factory/getChangeList</span>",
   dataType:'json',
   data: {
    "parentId":provinceId,
    "placeKbn":"C"
   },
   cache:false,
   success: function(data){
    if("success" == data.result){
     if(data.cityList != null && data.cityList.length > 0){
      for(var i = 0;i < data.cityList.length;i++){
       var city = data.cityList[i];
       var key = (city.key == null? "":city.key);
       var value = (city.value == null? "":city.value);
       $("#citySelect").append("<option value = \"" + key + "\">"+ value + "</option>");
      }
     }else{
      $("#citySelect").append("<option> </option>");
     }
     $("#areaSelect").append("<option> </option>");
    }
    if("error" == data.result){
     $("#citySelect").append("<option> </option>");
     $("#areaSelect").append("<option> </option>");
    }
   },
   error:function(XMLHttpRequest, textStatus, errorThrown){
       $("#errorContent").html("System abnormality, please contact the administrator");
      }
   
  });
 }else{
  $("#citySelect").append("<option> </option>");
  $("#areaSelect").append("<option> </option>");
 }
}
 
function cityChange(){
 
 var cityId = $("#citySelect").val();
 
 $("#areaSelect").empty();
 
 if(cityId != null && cityId != ""){
  
  $.ajax({
   type: "POST",
   url:"<span style="color:#3333ff;">factory/getChangeList</span>",
   dataType:'json',
   data: {
    "parentId":cityId,
    "placeKbn":"Q"
   },
   cache:false,
   success: function(data){
    if("success" == data.result){
     if(data.areaList != null && data.areaList.length > 0){
      for(var i = 0;i < data.areaList.length;i++){
       var area = data.areaList[i];
       var key = (area.key == null? "":area.key);
       var value = (area.value == null? "":area.value);
       $("#areaSelect").append("<option value = \"" + key + "\">"+ value + "</option>");
      }
     }else{
      $("#areaSelect").append("<option> </option>");
     }
    }
    if("error" == data.result){
     $("#areaSelect").append("<option> </option>");
    }
   },
   error:function(XMLHttpRequest, textStatus, errorThrown){
       $("#errorContent").html("System abnormality, please contact the administrator");
      }
   
  });
 }else{
  $("#citySelect").append("<option> </option>");
  $("#areaSelect").append("<option> </option>");
 }
}

Backend controller implementation code

@RequestMapping("<span style="color:#3333ff;">getChangeList</span>")
 @ResponseBody
 public Object getChangeList(String parentId,String placeKbn){
  logBefore(logger, "factory/getChangeList");
  Map<String,Object> returnMap = new HashMap<String,Object>();
  
  if (FactoryConsts.CHAR_KBN_CITY.equals(placeKbn)) {
   if(getPlacelist( parentId, placeKbn) != null && getPlacelist( parentId, placeKbn).size() > FactoryConsts.INT_0){
    returnMap.put("result", "success");
    returnMap.put("cityList", getPlacelist(parentId, placeKbn));
   }else{
    returnMap.put("error", "city list is empty");
    returnMap.put("cityList", "");
   }
   
  }else if(FactoryConsts.CHAR_KBN_AREA.equals(placeKbn)){
   if(getPlacelist( parentId, placeKbn) != null && getPlacelist( parentId, placeKbn).size() > FactoryConsts.INT_0){
    returnMap.put("result", "success");
    returnMap.put("areaList", getPlacelist(parentId, placeKbn));
   }else{
    returnMap.put("error", "area list is empty");
    returnMap.put("areaList", "");
   }
  }
  return returnMap;
 }
 /**
  *Province drop-down list* 
  * @return
  */
 private List<PlaceOption> getPlacelist(String parentId,String kbn){
  //Drop-down list List<PlaceOption> placeList = new ArrayList<PlaceOption>();
  placeList.add(new PlaceOption());
  QueryPlaceInfoParam queryParam = new QueryPlaceInfoParam();
  queryParam.setPlaceKbn(kbn);
  if(!StringUtils.isEmpty(parentId)){
   queryParam.setPlaceId(Integer.valueOf(parentId));
  }
  FactoryPlaceNameResult placeResult = placeInfoService.queryPlaceInfo(queryParam);
  
  if(placeResult != null && "0".equals(placeResult.getResult()) 
    && placeResult.getPlaceInfo() != null 
    && placeResult.getPlaceInfo().size() > FactoryConsts.INT_0){
   List<PlaceInfoFa> placeInfo = new ArrayList<PlaceInfoFa>();
   placeInfo = placeResult.getPlaceInfo();
   for(FactoryPlaceInfo info : placeInfo){
    PlaceOption option = new PlaceOption();
    option.setKey(String.valueOf(info.getPlaceId()));
    option.setValue(info.getPlaceName());
    placeList.add(option);
   }
  }
  
  return placeList;
 }

When clicking the menu at the same time, the controller implements the initial screen

/**
  * Basic information initialization method * 
  * @param request
  * @return
  */
 @RequestMapping("toFactoryBaseInfo")
 public ModelAndView toFactoryBaseInfo(HttpServletRequest request){
  logBefore(logger, "factory/toFactoryBaseInfo");
  ModelAndView mv = new ModelAndView();
  //Enterprise type Map<String,String> factoryTypeMap = new TreeMap<String,String>();
  factoryTypeMap.putAll(FactoryConsts.FACTORY_TYPE_MAP);
  mv.addObject("factoryTypeMap", factoryTypeMap);
  
  FactoryFactoryInfo factoryInfo = (FactoryFactoryInfo) request.getSession().getAttribute(Const.SESSION_FACTORY);
 
  //Get enterprise information FactoryFactoryInfoParam infoParam = new FactoryFactoryInfoParam();
             FactoryFactoryInfoResult infoResult = new FactoryFactoryInfoResult();
  infoParam.setFactoryId(String.valueOf(factoryInfo.getFactoryId()));
  infoParam.setDifferent(FactoryConsts.STRING_WEB_ONE); //web
  infoResult = factoryService.factoryInfo(infoParam);
 
  FactoryPlace factoryPlace = new FactoryPlace();
  
  <span style="color:#3333ff;">// Province drop-down list factoryPlace.setProvinceList(getPlacelist("0",FactoryConsts.CHAR_KBN_PROVINCE));
  // City drop-down list factoryPlace.setCityList(getPlacelist(infoResult.getFactoryInfoEx().getProvince(),FactoryConsts.CHAR_KBN_CITY));
  // Area drop-down list factoryPlace.setAreaList(getPlacelist(infoResult.getFactoryInfoEx().getCity(),FactoryConsts.CHAR_KBN_AREA));</span>
  
  <span style="color:#cc66cc;">mv.addObject("factoryPlace", factoryPlace);//List of addresses</span>
  <span style="color:#6633ff;">mv.addObject("factoryCenterInfo", infoResult.getFactoryInfoEx());//Basic information of the enterprise table</span>
  mv.setViewName("factory/factoryInformationCenter/saveFactoryBaseInfo");
  return mv;
 }

Multi-level linkage effects can be achieved.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Realizing provincial and municipal linkage effects based on JavaScript
  • JavaScript realizes the linkage effect between provinces and cities
  • JavaScript to achieve provincial and municipal linkage bug solution
  • Code sharing based on JS to achieve provincial and municipal linkage effect
  • js provincial and municipal linkage effect complete example code
  • JSON+HTML realizes the linkage selection effect of country, province and city
  • Province-city linkage menu implemented by JavaScript two-dimensional array
  • JavaScript provincial and municipal linkage implementation code
  • A simple example of using js to achieve the linkage effect between provinces and cities
  • javascript 2009 latest version of provincial and municipal linkage
  • js implements the method of selecting a value in the drop-down list (3 methods)
  • How to fill the content into the drop-down list after jquery uses ajax to get json data from the background
  • jquery+json universal three-level linkage drop-down list

<<:  How to configure VMware multi-node environment

>>:  Win10 installation of MySQL 5.7 MSI version of the tutorial with pictures and text

Recommend

JS asynchronous execution principle and callback details

1. JS asynchronous execution principle We know th...

Detailed explanation of creating and calling MySQL stored procedures

Table of contents Preface Stored Procedure: 1. Cr...

Share 8 MySQL pitfalls that you have to mention

MySQL is easy to install, fast and has rich funct...

Linux uses suid vim.basic file to achieve privilege escalation

Reproduce on Kali First set suid permissions for ...

MySQL database transaction example tutorial

Table of contents 1. What is a transaction? 2. Th...

How to mark the source and origin of CSS3 citations

I am almost going moldy staying at home due to th...

Ubuntu regularly executes Python script example code

Original link: https://vien.tech/article/157 Pref...

JavaScript to implement image preloading and lazy loading

This article shares the specific code for impleme...

Learn the basics of JavaScript DOM operations in one article

DOM Concepts DOM: document object model: The docu...

Detailed explanation of padding and abbreviations within the CSS box model

As shown above, padding values ​​are composite at...

In-depth discussion on auto-increment primary keys in MySQL

Table of contents Features Preservation strategy ...

MySQL 8.0.18 installation and configuration method graphic tutorial (linux)

This article records the installation and configu...

MySQL paging query optimization techniques

In applications with paging queries, queries that...