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

Implement QR code scanning function through Vue

hint This plug-in can only be accessed under the ...

Implementing timed page refresh or redirect based on meta

Use meta to implement timed refresh or jump of th...

js canvas realizes circular water animation

This article example shares the specific code of ...

How to deploy Spring Boot using Docker

The development of Docker technology provides a m...

How to import js configuration file on Vue server

Table of contents background accomplish Supplemen...

How to use VirtualBox to build a local virtual machine environment on Mac

1. Big Data and Hadoop To study and learn about b...

Introduction and use of js observer mode

Table of contents I. Definition 2. Usage scenario...

Detailed steps for quick installation of openshift

The fastest way to experience the latest version ...

How to elegantly implement WeChat authorized login in Vue3 project

Table of contents Preface Prepare Implementation ...

js to achieve a simple magnifying glass effect

This article shares the specific code of js to ac...

How to deploy and start redis in docker

Deploy redis in docker First install Docker in Li...

Detailed explanation of Linux redirection usage

I believe that everyone needs to copy and paste d...

JavaScript imitates Xiaomi carousel effect

This article is a self-written imitation of the X...

Basic tutorial on controlling Turtlebot3 mobile robot with ROS

Chinese Tutorial https://www.ncnynl.com/category/...