我在数据库中保存多行,所以我在jquery中的ajax调用中传递值。
$("button#submitbutton").click(function() {
var data = [];
var name, email, message;
$("table tbody tr").each(function(index) {
name = $(this).find('.name').text();
email = $(this).find('.email').text();
message = $(this).find('.message').text();
//---->Form validation goes here
data.push({
name: name,
email: email,
message: message
});
});
submitFormData(data);
});
function submitFormData(formData) {
var url= '/userrecords';
alert(url);
$.ajax({
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
beforeSend: beforeSendHandler,
url: url,
success: function(result){
if(result.success == true) {
$('.alert-success').show();
$('.alert-danger').hide();
$("#successmsg").html(result.msg);
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
} else {
$('.alert-danger').show();
$('.alert-success').hide();
$("#error").html(result.msg);
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
}
});
}
在Spring MVC中我写了控制器类
@RequestMapping(value = "/userrecords")
public @ResponseBody Response saveList(Model model)
throws ParseException, SQLIntegrityConstraintViolationException {
//read all values here
}
在控制器类中如何访问formData值。我对此并不了解。
答案 0 :(得分:0)
client side:
data: {model:formData.serialize()},
cache: false,
processData: false,
contentType: false
server side:1.> your api method should have the
same model structure
2.> then deserialize your model
3.> name of the object also be same like : model here
@RequestMapping(value = "/userrecords")
public @ResponseBody Response saveList(Model model)
throws ParseException, SQLIntegrityConstraintViolationException {
//read all values here
}
答案 1 :(得分:0)
需要纠正以下几点
POST
1>} @RequestMapping(value = "/userrecords,method=RequestMethod.POST")
装饰方法
Model
班级具有相同结构的姓名,电子邮件和消息 答案 2 :(得分:0)
创建dto模型(lombok +你可以使用@NotNull @Size(min = 1)代替@NotEmpty,如果你不想要hibernate依赖,你可以为有效的电子邮件实现自己的注释和验证器)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DataModel {
@NotEmpty
private String name;
@Email
private String email;
@NotEmpty
private String message;
}
在您的控制器中生成/使用指定请求/响应正文的类型,并且有效注释会在反序列化模型中触发字段验证。
@RequestMapping(value = "/userrecords", method = RequestMethod.POST,
consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE } )
@ResponseBody
public Response saveList(@Valid @RequestBody DataModel data, BindingResult result, Model data)
throws ParseException, SQLIntegrityConstraintViolationException {
//read all values here
}