[英]Form submission in spring using jquery
我的帶有彈簧標簽的表格:
<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調用:
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
$.ajax({
url : $("#form1").attr("action"),
type : "POST",
success : function(response) {
alert("success");
}
});
});
</script>
我的問題是如何將數據從jsp發送到控制器。 我的表格幾乎包含20個字段。
需要將@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;
}
並且也看到這個問題。
請嘗試此代碼
$.ajax({
data:$("#form1").serialize(),
url : $("#form1").attr("action"),
type : "POST",
success : function(response) {
alert("success");
}
});
試試這個代碼:
$("#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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.