百里香叶 + Spring Boot + HTML + 遍历列表中的列表



我对这个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列表应该在第三个选择框中加载。

我希望你理解这个问题。没有JS的简单代码会更受欢迎,但是如有必要,我们可以拥有JS函数。提前谢谢你。

好的,我能想到两种方法,但都需要一些 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>

现在,让我们为人员选择添加一个更改函数。

$('#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;    
}

另一种方法是使用百里香叶碎片来实现,但对于您的情况,我相信这样会更容易。无论哪种方式,都需要JS。希望对您有所帮助。

最新更新