是否可以在 Thymeleaf 模板内的 Javascript 函数中使用 Spring 模型?

Is it possible to use Spring model in Javascript functions inside Thymeleaf template?

我有以下域:

@Document(collection = "backupareas")
public class BackupArea {
    @Id
    private String id;

    private String area;

    private List<Tape> tapes;

在我的模板中,当我更改区域时,js 函数会用相关区域磁带填充 磁带 select。

<div class="form-group col-md-3">
   <label for="backup"><i>*</i> Backup</label>
   <select id="backup" class="form-control" name="backup" required onchange="loadTapes();">
       <option value="" selected="selected">--- Select Area ---</option>
       <option th:each="area: ${areas}" th:value="${area.getArea()}" th:text="${area.getArea()}"></option>
    </select>
</div>

<div class="form-group col-md-3">
    <label for="tape"><i>*</i> Tape</label>
    <select id="tape" class="form-control" name="tape" required >

    </select>

我从这个js函数开始,但我不知道如何使用(或者如果可能的话)模型变量。

function loadTapes() {
       var area = $("#backup").val();
       console.log($("#backup").index(area));

      if($("#backup").index(area) == 1) {
              $("#tape").empty();
              return false;
      }
      $("#tape").empty();

      var select = $('#tape');
      select.append($("<option />").val("").text("--- Select one ---"));
      // Here should use model variable to loop over tapes related to the selected area
      select.append($("<option/>").val(TAPE).text(TAPE));
            
  }
 

我解决了。我创建了一个片段:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<th:block th:fragment="tapes">
    <th:block th:if="${tapes != null}">
            <option th:each="tape: ${tapes}" th:value="${tape}" th:text="${tape}"></option>
    </th:block>
</th:block>
</body>
</html>

在主模板中,我调用了一个 ajax 方法:

function loadTapes() {
                     
      $("#tape").empty();
      $.post("/area/loadTapes", {area: area}, function (data) {
      $('#tape').append(data);
          });
}

loadTapes 方法是:

PostMapping("/area/loadTapes")
    public String loadTape(@RequestParam("area") String area, Model model) {
        BackupArea backupArea = backupAreaService.findByArea(area);
        List<Integer> tapes = new ArrayList<>();
        for(Tape tape: backupArea.getTapes()) {
            tapes.add(tape.getTape());
        }
        
        model.addAttribute("list", tapes);
        return "/backup/tapes :: list";
    }