JQuery Form表单转JSON(支持复杂数据版)

来源:互联网 发布:python re 匹配域名 编辑:程序博客网 时间:2024/05/16 08:36

关于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

}



修改前转换成JSON为:

{'name':'aaa','zone.id':1}

这种格式后台接收后zone是null


修改后JSON为:

{'name':'aaa','zone':{'id':1}}


这样后台接收就没有问题了,

有需要的可以借鉴


1 0
原创粉丝点击