首页 > 解决方案 > 使用 Javascript 从 Spring 访问特定的 Set 变量

问题描述

如何使用 Javascript 从 Spring 访问特定的 Set 变量?

我的控制器返回一个数据集,其中包含来自多个类的以下信息

Person
    String firstName;
    String lastName;
    int age;

Address
    String country;
    String city;

作为 model.addAttribute("personSet", form); 传递给 html

当它被传递给 html 时,数据变成这样:

Set1
 (from Person Class)
 firstName = John
 lastName = Doe
 age = 20
 
 (from Address Class)
 country = Japan
 city = Tokyo
 
Set 2
 (from Person Class)
 firstName = Mary
 lastName = Smith
 age = 30
 
 (from Address Class)
 country = Korea
 city = Seoul

我试图用 javascript 做的是我想获取特定的变量数据,以便我可以为集合中的每个项目执行 if 条件。例如:对于 personSet 中的每个人,如果 country = Japan,则打印 firstName + lastName。

为了解决这个问题,我创建了以下代码

请注意,我删除了一些变量声明,这是一个包含以下代码的内联 js 代码片段:

<script th:inline="javascript"> and /*<![CDATA[*/

    function printPeopleFromJapan() {
    //get the data of the whole set
    personSetJS = /*[[${personSet.Person}]]*/'default';
    
    //loop through all persons in the set
    for (person of personSet) {
        country = /*[[${personSet.country}]]*/'default';
            
        //if country is equal to Japan, get the person full name
        if (country == "Japan") {
            personFirstName = /*[[${personSet.firstName}]]*/'default';
            personLastName = /*[[${personSet.lastName}]]*/'default';
            console.log(personFirstName + personLastName);
        }
    }
}

但是我的程序没有运行,并且出现错误和空白页。

Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "personSet.Person" 

请帮忙。

标签: javascriptspring

解决方案


推荐阅读