如何使用modelAttribute在ajax(jquery)中提交spring表单

时间:2012-12-19 17:12:19

标签: java jquery spring jsp

我是Spring MVC的新手。 我有一个这样的表格,

<form:form action="/myaction.htm" method="post" modelAttribute="myForm" id="formid">和一个返回json的控制器

public @ResponseBody ResultObject doPost(@ModelAttribute("myForm") MyForm myForm){ System.out.println("myform.input"); }

我可以使用$("#formid").submit();提交此内容,并且我的modelAttribute工作正常,从UI中获取值。

我的问题是,如何以jquery ajax方式提交此表单? 我试过这个,

$.ajax({
type:"post",
url:"/myaction.htm",
async: false,
dataType: "json",
success: function(){
alert("success");
}

});

表单已提交,但modelAttribute值为空,如何在提交时包含modelAttribute对象(表单正在使用的对象)?

2 个答案:

答案 0 :(得分:53)

您需要发布数据。我通常使用以下方式。

var str = $("#myForm").serialize();

$.ajax({
    type:"post",
    data:str,
    url:"/myaction.htm",
    async: false,
    dataType: "json",
    success: function(){
       alert("success");
    }
});

答案 1 :(得分:2)

您的ModelAttributes未填充,因为您没有将任何参数传递给server.Form数据必须发布到服务器

$.post('myaction.htm', $('#formid').serialize())发送ajax帖子请求。