在Spring MVC中动态填充下拉列表 [英] Dynamically Populate Drop down List In Spring MVC

查看:159
本文介绍了在Spring MVC中动态填充下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring MVC的新手.我在Jsp中有两个下拉列表,一个是国家/地区,另一个是国家/地区.一旦我从列表中选择了国家,就应在国家列表中填充相应的列表.

I am new to Spring MVC. I have two Dropdown Lists in Jsp.One for country and Other for State. As soon as i select country from list State list should be populated with respective lists.

我的ajax程序:

 $("select#country").change(function() {
    var val=$("#country").val();
    alert(val);
    $.ajax({
    url : 'getstates',
    method : 'get',
    contentType: 'application/json',
     data :{
              country : val
            },

      success: function (data) {
      alert("Success Response"+ data);

      },

       error :function()
       {
               alert("error");
        }          

       });

我的控制器程序:

 public @ResponseBody HashMap<String, String> 
    showstates(@RequestParam(required = false, value =      "") 
    String country,@Valid    @ModelAttribute("employee")Login employee, 
    BindingResult result, ModelMap model) {  
    HashMap<String,String>  statelist = new HashMap<String,String>();
    List<States> statelist = new ArrayList<States>();
    if (country.equals("UnitedStates")) {
    statelist.put("Al","Alaska");
    statelist.put("Tl","Texas");
    } else if (country.equals("India")) {
    statelist.put("Mh","Maharashtra");
    statelist.put("WB","West Bengal");
    statelist.put("KR","Karnataka");
    statelist.put("AP","Andhra Pradesh");
    statelist.put("TN","Tamil Nadu");
    } 
    return statelist;
    }  

我没有收到控制器的响应.如何在jsp中访问hasmap.请帮我.谢谢.

I am not getting the response from controller. How to access the hasmap in jsp. Please Help me. Thanks.

推荐答案

您可以获取基于国家/地区的州列表:

You can obtain a list of states based on the country:

@Autowired
StateService stateService;

@GetMapping("/states")
public @ResponseBody List<State> getStates(@RequestParam String country) {
    return stateService.getStates(country) ;
}

您的州级类别将包含代码和名称;

your State class will contain code and name;

$("select#country").change(function() {
    var countryVal = $("#country").val();
    $.ajax({
       url : '/states?country='+countryVal,
       method : 'GET',
    },
    success: function (states) {
        var stateSelect = $('#state'); // the state select element
        stateSelect.find('option').remove();
        for (i = 0; i < states.length; i++) { 
            stateSelect.append("<option value=" + states[i].code + " >" + states[i].name + "</option>")
        }
    },

    error :function()
    {
       alert("error");
    }          

});

这篇关于在Spring MVC中动态填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆