【问题标题】:Populate dropdown2 based on the selection of dropdown1 in java spring annotation根据java spring注解中dropdown1的选择填充dropdown2
【发布时间】:2018-04-17 16:26:40
【问题描述】:

Java 代码包含以下内容:

@ModelAttribute("countries")
public List<Country> initializeCountries() {

    List <Country> countries = countryService.findAllCountrys();

    return countries;
}  

我已使用以下代码成功填充国家/地区:

<form:select path="country" id="country">
    <form:option value="">Select Country</form:option>
    <form:options items="${countries}" itemValue="countryCode" itemLabel 
     = "countryName" />
</form:select>
<form:errors path="country" cssClass="error"/> 

我有以下根据 countryCode 获取状态的代码:

List <State> states = countryService.findAllStatesOfCountry(countryCode);

我应该如何编写java代码和jsp代码来填充基于国家选择的状态下拉列表。在spring注解中不使用Ajax/javascript还有其他方法吗?试图找到这个选项。

如果不请提及完整的细节,因为我在 Ajax 方面已经尽力了。我是 Ajax 新手,因此请分享要加载到 jsp 文件中的 maven 依赖项、js 和 css 文件。

【问题讨论】:

    标签: java spring jsp spring-mvc spring-annotations


    【解决方案1】:

    不使用 ajax 也可以实现(虽然这里首选使用 ajax/javascript)。

     <script language="javascript">
         function getStates(selectedCountry)
         {
        window.location.href='/getStates?country='+selectedCountry; 
         }
    
         </script>
    
    <form:select path="country" id="country">
        <form:option value="">Select Country</form:option>
        <form:options items="${countries}" itemValue="countryCode" itemLabel 
         = "countryName" onchange="javascript:getStates(this.value)"/>
    </form:select>
    
        <form:select path="state" id="state">
            <form:option value="">Select State</form:option>
    <c:if test="${not empty states}" >
            <form:options items="${states}" itemValue="stateCode" itemLabel 
             = "stateName"/>
    </c:if>
        </form:select>
    
    • onchange 属性被添加到 javascript 函数调用中。它会 获取选定的国家/地区值并将其传递给具有 请求参数为country。因此,在更改国家/地区时,将进行服务器调用以获取给定国家/地区的状态,并且页面将被刷新。
    • 使用c:if 添加新的状态下拉列表,以便仅当属性states 存在时才会填充状态下拉列表 在请求中。

    在控制器端,您将编写如下内容

        @RequestMapping("/getStates")
            public ModelAndView getStates(@RequestParam("country")String countryCode){
           ModelAndView mv = new ModelAndView("yourCurrentView");     
    List<States> states = stateService.findAllStatesOfCountry(countryCode);
        mv.add("states",states);
        //to make sure countries drop down also has data
        mv.add("countries",countries);
        }
    

    【讨论】:

      猜你喜欢
      • 2016-12-25
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      相关资源
      最近更新 更多