也为每个相似的输入添加索引。
<input type="text" id="test1" name="steps[1][description]" value="one step">
<input type="text" id="test2" name="steps[2][description]" value="two step">
在表单提交时,您可以像这样调用 serializeObject 函数:
var data = $('#form' + formId).serializeObject();
this.model.save(data, {
success : function(model) {
},
error : function(model) {
}
});
您可以使用下面的 serializeObject 函数来解析上述语法。这与此stackoverflow 问题中解决的相同
$.fn.serializeObject = function() {
var json, patterns, push_counters, _this = 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] ===
void 0) {
push_counters[key] = 0;
}
return push_counters[key]++;
};
$.each($(this).serializeArray(), function(i, elem) {
var k, keys, merge, re, reverse_key;
if(!patterns.validate.test(elem.name)) {
return;
}
keys = elem.name.match(patterns.key);
merge = elem.value;
reverse_key = elem.name;
while(( k = keys.pop()) !==
void 0) {
if(patterns.push.test(k)) {
re = new RegExp("\\[" + k + "\\]$");
reverse_key = reverse_key.replace(re, '');
merge = _this.build([], _this.push_counter(reverse_key), merge);
} else if(patterns.fixed.test(k)) {
merge = _this.build([], k, merge);
} else if(patterns.named.test(k)) {
merge = _this.build({}, k, merge);
}
}
return json = $.extend(true, json, merge);
});
return json;
};
})(jQuery);