2013-03-30 22 views
-3

如何从序列化jquery中的对象获取正确的json结构?如何从序列化jQuery中的对象获取正确的json结构?

我的代码看起来是这样的:

<form id="myform"> 
<input name="Name[OrganizationName]" id="OrganizationName" /> 
</form> 

这是输出是这样的:

"Name[OrganizationName]": "Bill"} 

,但我想这一点:

"Name":{"OrganizationName":"Bill"} 

这里是我的系列化JS:

$.fn.serializeObject = 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; 
}; 

,我通过调用它:

$("#form-add-po").serializeObject(); 
+0

'名称= “名称[单位名称]”'看起来都是错误的。为什么不用'name =“OrganizationName”'或'name =“OrganizationName []”'为多个同名的字段? –

+0

粘贴无用的json作为帖子的主题是什么?非常有意义! – charlietfl

回答

0
$.fn.wrongLogic = function() { 
    var o = {}; 
    this.find('input').each(function() { 
     if (this.name.indexOf('[') > -1) { 
      var prop = this.name.match(/\[(\w+)\]$/)[1], 
       mainProp = this.name.split('[')[0], 
       n = {}, 
      if (o.hasOwnProperty(mainProp)) { 
       o[mainProp][prop] = this.value; 
      } else { 
       n[prop] = this.value; 
       o[mainProp] = n; 
      } 
     } else { 
      o[this.name] = this.value; 
     } 
    }) 
    return o; 
}; 

http://jsfiddle.net/h2jE5/1/

相关问题