我有以下表格......
<form id="my-form">
<fieldset name="address">
<input name="streetAddress" type="text" placeholder="Street Address"><br>
<input name="city" type="text" placeholder="City"><p>,</p>
<input name="state" type="text" placeholder="State">
<input name="zipCode" type="text" placeholder="Zip Code">
</fieldset>
<fieldset name="dimensions">
<input name="length" type="text" placeholder="length">
<input name="width" type="text" placeholder="width">
<input name="height" type="text" placeholder="height">
</fieldset>
</form>
我需要使用JS将其序列化为JSON,但是我需要在地址对象中将地址的字段扭曲,并且维度的字段在维度对象中变形。
像这样......
{
'address':{'streetAddress':'111 Candy Ln', 'city':'Los Angeles', ...},
'dimensions':{...}
}
如何干净利落地完成这项工作,理想情况下无需编写我自己的功能来执行此操作?我当然看到了要序列化的脚本,但没有任何可以做嵌入式对象的脚本。
答案 0 :(得分:2)
您是否尝试将所有字段放入数组?
<fieldset name="address">
<input name="address[streetAddress]" type="text" placeholder="Street Address"><br>
<input name="address[city]" type="text" placeholder="City"><p>,</p>
<input name="address[state]" type="text" placeholder="State">
<input name="address[zipCode]" type="text" placeholder="Zip Code">
</fieldset>
下面是一个使用serializeObject插件的例子
只需包含该脚本,即可将任何表单转换为多层JSON对象。
使用此插件...更多信息Convert form data to JavaScript object with jQuery
(function($){
$.fn.serializeObject = function(){
var self = this,
json = {},
push_counters = {},
patterns = {
"validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
"key": /[a-zA-Z0-9_]+|(?=\[\])/g,
"push": /^$/,
"fixed": /^\d+$/,
"named": /^[a-zA-Z0-9_]+$/
};
this.build = function(base, key, value){
base[key] = value;
return base;
};
this.push_counter = function(key){
if(push_counters[key] === undefined){
push_counters[key] = 0;
}
return push_counters[key]++;
};
$.each($(this).serializeArray(), function(){
// skip invalid keys
if(!patterns.validate.test(this.name)){
return;
}
var k,
keys = this.name.match(patterns.key),
merge = this.value,
reverse_key = this.name;
while((k = keys.pop()) !== undefined){
// adjust reverse_key
reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');
// push
if(k.match(patterns.push)){
merge = self.build([], self.push_counter(reverse_key), merge);
}
// fixed
else if(k.match(patterns.fixed)){
merge = self.build([], k, merge);
}
// named
else if(k.match(patterns.named)){
merge = self.build({}, k, merge);
}
}
json = $.extend(true, json, merge);
});
return json;
};
})(jQuery);
答案 1 :(得分:1)
我有两个解决方案:
address[street], address[zipcode], etc
。在这两种情况下,我建议你使用我制作的这个库:https://github.com/serbanghita/formToObject
这样称呼:
案例1:var myFormObj = new formToObject('myFormId');
案例2:var myFormObj = new formToObject('myFieldsetId');