thymeleaf form ajax,jquery – 推荐的方式来处理Thymeleaf Spring MVC AJAX Forms及其错误消息...

我想做的是在发生错误时更换整个表单.以下是超原始示例.我不会使用大量的片段来呈现一个表单…只是保持简单.

这是写在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;

}

控制器: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";

}

}

用于呈现表单和成功消息的文件:fragments / user.html

First Name

Email

Form successfully submitted

JS代码将简单地将表单提交到表单action属性中提供的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));

再次,这只是一个基本的例子.如上述评论中所提到的,没有正确的或错误的方法来解决这个问题.这不是我的首选解决方案,绝对有一些调整,我会做,但一般的想法是在那里.

注意:我的JS代码中还有一个缺陷.如果将表单与响应中的表单替换,则表单提交处理程序将不会应用于新替换的表单.如果进入此路由,则需要确保在更换表单后正确重新初始化表单处理程序.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值