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

问题描述:

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

I am new to Spring MVC. I have a form like this,

< form:form acion =/ myaction.htmmethod =post modelAttribute =myFormid =formid> 和一个返回json的控制器

<form:form acion="/myaction.htm" method="post" modelAttribute="myForm" id="formid"> and a controller that returns json

public @ResponseBody ResultObject doPost(@ModelAttribute(myForm)MyForm myForm){
sysout(myform.input);
}

我可以使用 $(#formid)提交此项。(提交) ); 和我的modelAttribute工作正常,从UI中获取值。

I am able to submit this using$("#formid").submit(); and my modelAttribute is working fine, taking values from UI.

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

my question is, how to submit this form in jquery ajax way? I tried this,

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

});

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

the form is submitted but modelAttribute values are nulls, how to include modelAttribute object(object that form is using) while submitting?

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

You need to post the data. The way I typically do it is using the following.

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

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