标签:div content $.ajax 接收参数 tostring 需要 lsp ges use
前端代码:
<form id="person_add" method="post" action="user"> <table class="table_add"> <tr> <td> </td> <td>name:</td> <td><input name="name" value=""/></td> <td>address</td> <td><input name="address" value=""/></td> </tr> <tr> <td></td> <td>name:</td> <td><input name="name" value=""/></td> <td>address</td> <td><input name="address" value=""/></td> </tr> <tr> <td></td> <td>name:</td> <td><input name="name" value=""/></td> <td>address</td> <td><input name="address" value=""/></td> </tr> <tr> <td></td> <td>name:</td> <td><input name="name" value=""/></td> <td>address</td> <td><input name="address" value=""/></td> </tr> <tr align="center"> <td colspan="5"> <a id="menu_submit" href="javascript:onSubmit()">提交</a> <a id="menu_no" href="javascript:closeDialog()">关闭</a> </td> </tr> </table> </form>
Controller代码:
@PutMapping public void addUser(@RequestBody List<Person> persons){ System.out.println(persons.toString()); }
如果后台使用Controller这样接收参数,那么必须传递进来参数如下格式:
[{"name":"1","address":"a1"},{"name":"2","address":"b1"},{"name":"3","address":"c1"},{"name":"4","address":"d1"}]
首先对表单进行序列化,
$.serializeObject = function (form) { var o = {}; $.each(form.serializeArray(), function (index) { if (o[this[‘name‘]]) { if ($.isArray(o[this[‘name‘]])) { o[this[‘name‘]].push(this[‘value‘]); } else { o[this[‘name‘]] = [o[this[‘name‘]], this[‘value‘]]; } } else { o[this[‘name‘]] = this[‘value‘]; } }); return o; };
序列化之后的表单是一个对象,通过调用,得到一个对象
var serializeArray = $.serializeObject($("#person_add"));
将对象分解成为我们需要的json字符串,JSON.stringify() 将对象转为字符串
// 计算json内部的数组最大长度,必须要有这一步 for (var item in serializeArray) { var tmp = $.isArray(serializeArray[item]) ? serializeArray[item].length : 1; vCount = (tmp > vCount) ? tmp : vCount; } if (vCount > 1) { var jsonData2 = new Array(); for (var i = 0; i < vCount; i++) { var jsonObj = {}; for (var item in serializeArray) { jsonObj[item] = serializeArray[item][i]; } jsonData2.push(jsonObj); } jsonParams=JSON.stringify(jsonData2); } else { jsonParams=JSON.stringify(serializeArray); }; console.info(jsonParams);
得到的jsonParams就是我们需要的json字符串
通过ajax直接上传即可:
$.ajax({ url: "user", method: "PUT", contentType: "application/json; charset=utf-8", data: jsonParams, success: function (res) { alert(res); } })
【springmvc】之使用jQuery接收前端传入List对象
标签:div content $.ajax 接收参数 tostring 需要 lsp ges use
原文地址:http://www.cnblogs.com/gyjx2016/p/7772195.html