gpt4 book ai didi

java - 动态填充 thymeleaf 中的列表

转载 作者:行者123 更新时间:2023-12-02 09:04:12 34 4
gpt4 key购买 nike

在 Spring MVC 项目的 Controller 中,我确实有一个放入模型映射的列表,如下所示。

@GetMapping("/teacher/{userId}/add_thiesis")
public String dashboard(ModelMap model, @PathVariable Long userId) {

List<Course> courses = courseRepo.findAll();
model.put("courses", courses);

String uId = String.valueOf(userId);

ArrayList<String> questions = new ArrayList<>();
model.put("id", uId);
model.put("thiesis", new Thiesis());
model.put("questions",questions);
return "add_thiesis";
}

现在我想在 thymeleaf View 中使用 post 方法动态填充它。为此,我使用 JavaScript 脚本。这不是全部 html 代码,但为了简单起见,我只添加了 JS 部分。

    window.addEventListener("load", start);
var i='0';




var question = '<div class="form-group row">'+
'<label for="name" class="col-12 col-sm-4 col-form-label">Question:</label>'+
'<div class=" col-12 col-sm-8">'+
'<input type="text"'+ ' class="form-control" placeholder="Enter question here..." th:field="{questions['+i+']"} required/><br/>'+
'</div>'+
'</div>';

function start(){
var plus = document.getElementById("plus");
var minus = document.getElementById("minus");


plus.addEventListener("click", add);
minus.addEventListener("click", remove);
}


function add(){
var addQuestion = document.getElementById("question_body");
addQuestion.innerHTML += question;
i++;
console.log(i);
}

function remove(){
var removeQuestion = document.getElementById("question_body");
if(i>0){
console.log(removeQuestion.lastChild.nodeName);
removeQuestion.removeChild(removeQuestion.lastChild);
i--;
console.log(i);
}

}

这是经过测试可以正常工作的 post 方法。

    @PostMapping("/teacher/{userId}/add_thiesis")
public String addThiesis(Thiesis thiesis, ArrayList<String> questions)
{
for (String question : questions) {
Question q = new Question();
q.setQuestion(question);
questionService.save(q);
}
System.out.println("addThiesis called");
String tmpCourse = thiesis.getTmpCourse();
thiesisService.save(thiesis, tmpCourse);
System.out.println(thiesis.getId());
return "" ;
}

它向我显示错误:解析模板 [] 时出错,模板可能不存在,或者可能无法被任何配置的模板解析器访问,这肯定是因为:th:field="{questions['+i+']" 。有没有办法动态填充数组,因为添加的问题数量是一个变量。有没有办法处理它?

最佳答案

在 GET 方法中尝试一下:

return "add_thiesis.html";

并像这样使用 @Controller 注释:

@Controller
public class YourClass {
//
}

编辑:

此外,th:field 也有一个小错误

th:field="'*{questions['+i+']}'"

关于java - 动态填充 thymeleaf 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59957582/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com