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

Ron*_*ony 14 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");
}

});
Run Code Online (Sandbox Code Playgroud)

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

Man*_*nes 53

您需要发布数据.我通常这样做的方式是使用以下方法.

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

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

  • @Rony如果它适合您,请不要忘记将其标记为已接受. (10认同)

ssk*_*ssk 2

您的 ModelAttributes 未填充,因为您没有将任何参数传递到服务器。表单数据必须发布到服务器

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