我对这个Spring Boot + Thymeleaf很陌生。抱歉,如果重复此问题,但我找不到任何答案。
以下是一些代码示例:
public class PersonPOJO {
private String uniqID;
private List<AddressPOJO> addresses;
// And Some other fields and setters and getters
private List<String> someList;
}
public class AddressPOJO {
private String uniqAddId;
private List<String> someList;
// And Some other fields and setters and getters
}
我省略了URL映射和配置注释。请忍受我。
public class ControllerClass {
public String htmlLoadMethod(Model model) {
// personsList is List<PersonPOJO>. I'm having them from global.
model.addAttribute("persons", personsList);
return "viewName";
}
}
现在进入我的HTML页面:假设“ viewName”
<form action="#">
<select required="required">
<option th:each="person : ${persons}" th:value="${person.uniqID}" th:text="${person.uniqID}"></option>
</select>
<select>
<!-- Load addresses (uniqAddIds) of the specific person I've selected in first select BOX -->
</select>
<select required="required">
<!-- Load list of Strings of the specific addresses I've selected in addresses select BOX -->
</select>
</form>
这里还有一个问题,有时候我在某些PersonPOJO中确实将地址列表设置为空。在这种情况下,应禁用地址选择框。并且应该将PersonPOJO的someList加载到第三个选择框中。
希望您能理解问题。一个没有JS的简单代码将受到更多的赞赏,但是如果有必要,我们可以拥有JS函数。预先谢谢你。
答案 0 :(得分:0)
好吧,我可以想到两种方法,但是都需要一些JS。最简单的方法是发送Ajax请求并获取地址列表。首先,对您的html进行一些修改,我们需要添加一些ID以使其变得更容易。
<form action="#">
<select id="persons" required="required">
<option th:each="person : ${persons}" th:value="${person.uniqID}" th:text="${person.uniqID}"></option>
</select>
<select id="addresses">
<!-- Load addresses (uniqAddIds) of the specific person I've selected in first select BOX -->
</select>
<select required="required">
<!-- Load list of Strings of the specific addresses I've selected in addresses select BOX -->
</select>
</form>
现在,我们为人员选择项添加一个on change功能。
$('#persons').on('change', function() {
var value = $(this).val();
$.ajax({
url: '/get-address',
data: {personId: value},
type: 'GET',
success: function(address) {
var addressList = $('$addresses');
// Clear old data.
addressList.empty();
// Iterate through all the fetched addresses and append them.
$.each(address, function() {
addressList.append('<option value="'+address.uniqAddId +'"></option>');
});
}, error: function() {
alert("Error loading the addresses.");
}
})
});
现在,您需要在控制器中添加一个看起来像这样的新方法。
@RequestMapping(value = "/get-addresses", method = RequestMethod.GET)
@ResponseBody
public List<Addresses> fetchAddresses(@RequestParam("personId") String personId) {
// Fetch the addresses using the person's id.
return addresses;
}
使用Thymeleaf片段可以实现另一种方法,但是对于您的情况,我相信这种方法会更容易。无论哪种方式,都需要JS。希望对您有所帮助。