带list子表单转json
例如 :
a:123,b:123,c[0].aaa:123,c[0].bbb:234,c[1].aaa:123,c[2].bbb:234
转为:
{
"a": 123,
"b": 123,
"c": [{
"aaa": 123,
"bbb": 234
}, {
"aaa": 123,
"bbb": 234
}]
}
function goSubmit() {
$.ajax({
url: 'xxxxxxxxxxxxx',
data: JSON.stringify(serializeObject($('#form1'))),
dataType: "json",
contentType: "application/json",
async: true,
type: "post",
success: function (data) {
}
})
}
function serializeObject(form) {
var obj = {};
var a = form.serializeArray();
$.each(a, function () {
if (this.name.indexOf("[") !== -1 && this.name.indexOf("].") !== -1) {
let temp1 = this.name.split("[");
let temp2 = temp1[1].split("].");
let list_name = temp1[0];
let list_index = parseInt(temp2[0]);
let list_key = temp2[1];
// console.log(list_name, '-', list_index, '-', list_key)
if (obj[list_name]) {
// console.log(obj[list_name])
let arr = obj[list_name]
if (arr.length < list_index + 1) {
for (let i = arr.length; i < list_index + 1; i++) {
// console.log(list_index + 1)
let list_obj_temp = {}
arr.push(list_obj_temp)
}
}
let list_obj = obj[list_name][list_index];
list_obj[list_key] = this.value || '';
} else {
let arr = []
if (list_index !== 0) {
for (let i = 0; i < list_index + 1; i++) {
// console.log(list_index + 1)
let list_obj_temp = {}
arr.push(list_obj_temp)
}
}
let list_obj = {}
list_obj[list_key] = this.value || '';
arr.push(list_obj)
obj[list_name] = arr;
}
} else {
if (obj[this.name]) {
if (!obj[this.name].push) {
obj[this.name] = [obj[this.name]];
}
obj[this.name].push(this.value || '');
} else {
obj[this.name] = this.value || '';
}
}
});
return obj;
}