ThymeLeaf:我如何将从我的服务器发送的模型属性传递给来自Thymeleaf的JS

时间:2018-05-03 17:07:27

标签: spring-boot thymeleaf

我发送通过模型属性

从服务器向百万富翁发送一个列表
friendsOnlineModel.setFriendsOnline(defaultFriendRequestService.getFriendsOnline(user) == null ? Collections.EMPTY_LIST : defaultFriendRequestService.getFriendsOnline(user));

    chatModel.setChats(defaultChatService.getUnreadChats() == null ? Collections.EMPTY_LIST : defaultChatService.getUnreadChats());

    model.addAttribute("friends_online", friendsOnlineModel);

    model.addAttribute("chats", chatModel);

我不想直接在" li"标记,而是将其传递给显示它们的js函数。有可能吗?

1 个答案:

答案 0 :(得分:3)

有几种方法可以做到这一点。您可以使用JavaScript inlining,并将数据直接添加到您的网页中。与示例类似:

<script th:inline="javascript">
    var fiendsOnline = [[${friends_online}]];
    var chats = [[${chats}]];
</script>

然后你可以用javascript来处理它们,无论你想要什么。

或者,您可以将它们添加到使用@ResponseBody注释的其他控制器方法,而不是将这些属性放在模型上。然后使用ajax调用该方法,Spring将您的对象作为JSON返回。