Kri*_*tof 13 ajax jquery spring spring-mvc thymeleaf
在Thymeleaf方面处理AJAX表单及其错误消息的推荐方法是什么?
我目前有一个Spring控制器,它返回字段的JSON概述及其各自的错误消息,但不得不求助于使用完全手写的JQuery(或只是常规的Javascript)只是感觉有点不对,而且速度慢; 特别是因为我打算在应用程序中使用大量的表单.
小智 23
我喜欢做的是在发生错误时替换整个表单.以下是一个超级原始的例子.我不会使用大量的片段来渲染表格......只是保持简单.
这是用Spring 4.2.1和Thymeleaf 2.1.4编写的
表示用户信息表单的基本类:UserInfo.java
package myapp.forms;
import org.hibernate.validator.constraints.Email;
import javax.validation.constraints.Size;
import lombok.Data;
@Data
public class UserInfo {
@Email
private String email;
@Size(min = 1, message = "First name cannot be blank")
private String firstName;
}
Run Code Online (Sandbox Code Playgroud)
控制器:UsersAjaxController.java
import myapp.forms.UserInfo;
import myapp.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
@Controller
@Transactional
@RequestMapping("/async/users")
public class UsersAjaxController {
@Autowired
private UserServices userServices;
@RequestMapping(value = "/saveUserInfo", method = RequestMethod.POST)
public String saveUserInfo(@Valid @ModelAttribute("userInfo") UserInfo userInfo,
BindingResult result,
Model model) {
// if any errors, re-render the user info edit form
if (result.hasErrors()) {
return "fragments/user :: info-form";
}
// let the service layer handle the saving of the validated form fields
userServices.saveUserInfo(userInfo);
return "fragments/user :: info-success";
}
}
Run Code Online (Sandbox Code Playgroud)
用于呈现表单和成功消息的文件:fragments/user.html
<div th:fragment="info-form" xmlns:th="http://www.thymeleaf.org" th:remove="tag">
<form id="userInfo" name="userInfo" th:action="@{/async/users/saveUserInfo}" th:object="${userInfo}" method="post">
<div th:classappend="${#fields.hasErrors('firstName')}?has-error">
<label class="control-label">First Name</label>
<input th:field="*{firstName}" type="text" />
</div>
<div th:classappend="${#fields.hasErrors('first')}?has-error">
<label class="control-label">Email</label>
<input th:field="*{email}" ftype="text" />
</div>
<input type="submit" value="Save" />
</form>
</div>
<div th:fragment="info-success" xmlns:th="http://www.thymeleaf.org" th:remove="tag">
<p>Form successfully submitted</p>
</div>
Run Code Online (Sandbox Code Playgroud)
JS代码只需将表单提交到表单操作属性中提供的URL即可.当响应返回到JS回调时,检查是否有任何错误.如果有错误,请将表单替换为响应中的表单.
(function($){
var $form = $('#userInfo');
$form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: $form.attr('action'),
type: 'post',
data: $form.serialize(),
success: function(response) {
// if the response contains any errors, replace the form
if ($(response).find('.has-error').length) {
$form.replaceWith(response);
} else {
// in this case we can actually replace the form
// with the response as well, unless we want to
// show the success message a different way
}
}
});
})
}(jQuery));
Run Code Online (Sandbox Code Playgroud)
同样,这只是一个基本的例子.如上面的评论所述,没有正确或错误的方法来解决这个问题.这也不是我首选的解决方案,我肯定会做一些调整,但总体思路就在那里.
注意:我的JS代码也存在缺陷.如果将表单替换为响应中的表单,则表单提交处理程序将不会应用于新替换的表单.您需要确保在更换表单后正确地重新初始化表单处理程序(如果使用此路由).
归档时间: |
|
查看次数: |
19882 次 |
最近记录: |