【发布时间】:2020-01-28 21:52:02
【问题描述】:
在 Spring MVC 项目的控制器中,我确实有一个列表,我将其放入模型映射中,如下所示。
@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";
}
现在我想在百里香视图中使用 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+']"。
有没有办法动态填充数组,因为添加的问题数量是一个变量。有没有办法处理它?
【问题讨论】:
标签: java spring model-view-controller thymeleaf