在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");
}
});