【发布时间】:2020-05-24 14:39:01
【问题描述】:
我在 Bootstrap 模式中有一个 Thymeleaf 表单,我想用 jQuery - Ajax 调用来处理它。 表单如下所示:
<form th:action="@{/model/new}" th:method="POST" th:object="${modelForm}" id="form-new-model">
<div class="form-group">
<label for="name"><strong>Model name</strong></label>
<input type="text" class="form-control" th:classappend="${#fields.hasErrors('name')} ? is-invalid : '' " th:field="*{name}" aria-describedby="name" placeholder="My awesome model">
<div class="invalid-feedback" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Error name</div>
</div>
<div class="form-group">
<label for="description"><strong>Model description (optional)</strong></label>
<textarea class="form-control" th:field="*{description}" rows="3" placeholder="Description"></textarea>
</div>
<div class="form-group row border-top align-items-center mb-0">
<div class="col text-right mt-2">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Add</button>
</div>
</div>
</form>
在控制器中我有以下内容:
@PostMapping("/model/new")
public String newModel(@Valid modelForm modelForm, BindingResult bindingResult, RedirectAttributes attributes) {
if(bindingResult.hasErrors()){
attributes.addFlashAttribute("org.springframework.validation.BindingResult.dexModelForm", bindingResult);
attributes.addFlashAttribute("modelForm", modelForm);
return "project/modal-new-model";
}
// creating the object since it is valid
// and returning success response with the new updated view
return "";
}
因此,由于我正在使用 jQuery 处理表单,因此我有:
$(document).on('submit', '#form-new-model', function(e){
e.preventDefault();
const csrf = $(this).find('input[name="_csrf"]').val();
$.ajax({
type: 'POST',
url: '/model/new',
headers: {'csrf-token':csrf},
data: $(this).serializeArray(),
cache: false,
success: function(data){
// Here the controller needs to bring me a Success Response (No error).
// And then I refresh specific parts of the whole view.
},
error: function(data){
// I need first to bring 'SOMETHING' from the controller that says is an error.
// Here I have to update the form since I will return a view from the controller.
}
});
});
所以现在的问题是如何从控制器控制它是什么响应,并与响应一起发送特定的 HTML/Thymeleaf 视图?
【问题讨论】:
-
ajax请求后,你想做什么?将 thymeleaf 页面的一部分发送到前端并将其与文档一起附加到同一页面中?或者你想路由不同的百里香视图?
-
是的,我想要一个 thymeleaf 布局或一个视图/模板,当出错以及何时成功我想路由到不同的视图。
标签: jquery ajax spring spring-boot spring-mvc