带有弹簧标签的表格:
<form:form action="save" commandName="user" id="form1">
<form:input
.
.
<form:select
.
.
<input type="submit" value="Submit" />
</form:form>
控制器:
@RequestMapping(value="/save",method = RequestMethod.POST)
public @ResponseBody UserEntity dataSave(@ModelAttribute("user") UserEntity user, BindingResult result) {
userManager.addUser(user);
return user;
}
jquery call:
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
$.ajax({
url : $("#form1").attr("action"),
type : "POST",
success : function(response) {
alert("success");
}
});
});
</script>
我的问题是如何将数据从jsp发送到控制器。我的表格几乎包含20个字段。
答案 0 :(得分:0)
需要将@ResponseStatus(HttpStatus.NO_CONTENT)
添加到Spring MVC控制器方法
例如
@RequestMapping(value="/save",method = RequestMethod.POST)
@ResponseStatus(HttpStatus.NO_CONTENT)
public @ResponseBody UserEntity dataSave(@ModelAttribute("user") UserEntity user, BindingResult result) {
userManager.addUser(user);
return user;
}
另见this问题。
答案 1 :(得分:0)
请尝试此代码
$.ajax({
data:$("#form1").serialize(),
url : $("#form1").attr("action"),
type : "POST",
success : function(response) {
alert("success");
}
});
答案 2 :(得分:0)
试试这段代码:
$("#form1").submit(function(event){
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /action
request = $.ajax({
url: "/app/action",
type: "post",
data: serializedData,
success: function(response){
// we have the response
alert(response);
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
$inputs.prop("disabled", false);
console.log("Form1 Posted");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
$inputs.prop("disabled", false);
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});