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

时间:2020-12-28 20:35:07

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

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

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

以及一个返回json的控制器

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

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

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

我可以使用$(“#formid”)提交.admin();我的modelAttribute运行正常,从UI中获取值。

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

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

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

});

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

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

2 个解决方案

#1


52  

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");
    }
});

#2


2  

your ModelAttributes are not populated as you are not passing any params to server.Form data has to be posted to server

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

$.post('myaction.htm', $('#formid').serialize()) to send ajax post request.

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

#1


52  

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");
    }
});

#2


2  

your ModelAttributes are not populated as you are not passing any params to server.Form data has to be posted to server

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

$.post('myaction.htm', $('#formid').serialize()) to send ajax post request.

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