我可以结合Ajax使用Spring表单标记库吗?我无法在控制器中成功检索表单输入参数,它们总是空的。
实际上,表单从来没有提交过,这是一种逻辑。但是,我只能向控制器发送字符串,而不能像映射到Spring commandBean的表单提交那样发送对象。
表单接受commandBean:
<form:form method="POST" commandName="clinicBean">
Clinic Name: <form:input path="name" type="text" /><br/>
Clinic Address: <form:input path="address" type="text"/><br/>
<input type="button" value="Create Clinic" onclick="clinicAjax()"/>
</form:form>
Ajax函数调用Spring控制器:
function clinicAjax(){
alert('Inside Clinic Ajax Method');
$.ajax({
url: 'clinicAjax',
type: 'POST',
success: alert('Ajax Successful')
});
}
Spring Controller 方法:
@RequestMapping(value="clinicAjax",method=RequestMethod.POST)
public @ResponseBody String createClinic(@ModelAttribute("clinicBean") Clinic clinic){
System.out.println("Ajax call successful");
System.out.println(clinic);
System.out.println(clinic.getName());
System.out.println(clinic.getAddress());
return "SUCCESS";
}
它总是在System.out.println()语句中获得NULL。
The problem is that you're not serializing your form anywhere so it's not being sent to the server.
Change your javascript code to:
function clinicAjax(){
alert('Inside Clinic Ajax Method');
$.ajax({
url: 'clinicAjax',
data: yourFormElement.serialize(); /* i.e. $('#formId').serialize(); */
type: 'POST',
success: alert('Ajax Successful')
});
}
substitute yourFormElement
with jQuery object representing your form and it should work.