关于Form表单转封装JSON的网上又很多,但是目前没找到可以封装Object嵌套的,所以稍微修改了下
网上通常写法:
$.fn.toJSON = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$.fn.toJSON = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
var name = this.name;
var value = this.value;
var paths = this.name.split(".");
var len = paths.length;
var obj = o;
$.each(paths,function(i,e){
if(i == len-1){
if (obj[e]) {
if (!obj[e].push) {
obj[e] = [obj[e]];
}
obj[e].push(value || '');
} else {
obj[e] = value || '';
}
}else{
if(!obj[e]){
obj[e] = {};
}
}
obj = o[e];
});
});
return o;
};
Form表单如下:
<f:form id="form" commandName="manager" autocomplete="false">
<div class="row">
<f:input path="name" class="form-control" />
<f:input path="zone.id" class="form-control" />
</div>
</f:form>
后台JAVA对象是
public class User{
private String name;
private Zone zone;
.//..get / set
}
public class Zone {
private Long id;
// ...get / set
}
{'name':'aaa','zone.id':1}
修改后JSON为:
{'name':'aaa','zone':{'id':1}}
有需要的可以借鉴